dr24
1 week ago

Problem with accessing table columns from models in search function

Posted 1 week ago by dr24

I have a search function that can search users based on filters that user inputs (from/to age, from/to height). Problem is that age column is in users table (User model) and height column is in user_profiles table (UserProfile model). I can get results from each model individually easy but I want to fetch results when I combine those two conditions. For example, fetch users with age 30 to 40 years old that are between 180 cm and 190 cm. Any help is appreciated. Here is my code.

SearchController.php

class SearchController extends Controller
{
    public function search(Request $request, User $user)
    {
        $query = User::query();   // HERE I NEED TO FETCH USER PROFILE COLUMNS FROM MODEL ALONG WITH USER
        dd($query);

        // HEIGHT SETTING
        if ($request->has('from_cm')) {
            $request->get('from_cm');
        }

        if ($request->has('to_cm')) {
            $request->get('to_cm');
        }

        if ($request->from_cm && $request->to_cm) {
            $query->whereBetween('height', [$request->from_cm, $request->to_cm]);
        } elseif ($request->from_cm) {
            $query->where('height', '>=', $request->from_cm);
        } elseif ($request->to_cm) {
            $query->where('height', '<=', $request->to_cm);
        }

        // AGE SETTING
        if ($request->has('from_age')) {
            $request->get('from_age');
        }

        if ($request->has('to_age')) {
            $request->get('to_age');
        }

        if ($request->from_age && $request->to_age) {
            $query->whereBetween('age', [$request->from_age, $request->to_age]);
        } elseif ($request->from_age) {
            $query->where('age', '>=', $request->from_age);
        } elseif ($request->to_age) {
            $query->where('age', '<=', $request->to_age);
        }

        $results = $query->get();
        //dd($results);
    }
}

User.php

protected $fillable = [
        'username', 
        'email', 
        'first_name',
        'last_name',
        'age',
    ];  

public function userProfile()
{
    return $this->hasOne(UserProfile::class);
}

UserProfile.php

protected $fillable = [
        'user_id',
        'interested_in',
        'height',
      
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

So, to be clear I don't need particular user with his user profile but joined columns from user and user profile models in one variable ($query).

Please sign in or create an account to participate in this conversation.