0

Hi guys I am new in Laravel I want your help. Here is my database:

user: id, name, surname, email, role

user_informations: id, user_id, status

I want the name of all users where status is enable.

What I do is this:

User.php

public function information()
    {
        return $this->hasOne('App\UserInformation');
    }

UserInformation.php

 public function guider()
    {
        return $this->belongsTo('App\User');
    }

This is my query:

 $users =User::where('role', '2')->information()->get();

Call to undefined method Illuminate\Database\Eloquent\Builder::information()

I know my query is wrong, because i ahve not defined anywhere that i want to get all users that have their status 'enable'

Alphal1111
  • 99
  • 3
  • 13

3 Answers3

1

You should use whereHas() the first parametr of this method is your relation and second one is your callback function

$users =User::where('role', '2')->whereHas('information',function($query){
    return $query->where('status','enable')
})->get();
Saman Ahmadi
  • 677
  • 3
  • 9
0

You need to use with

$users = User::where('role', '2')->with('information')->get();

or

$users =User::where('role', '2')->get();

foreach($users as $user) {
    dump($user->information);
}
Jagadesha NH
  • 2,529
  • 2
  • 23
  • 41
0

To get all users who have 'enable' status and '2' role:

$users = User::where('role', '2')->with(['information' => function($query) {
         $query->where('status', 'enable');
}])->get();

You can find more details on Laravel docs with Eager Loading keyword.

Also you can read this topic to learn how it works.