简体   繁体   中英

laravel Auth::user()->with return all not just authenticated user

wrong: this return all Users with their persons:

$me = Auth::user()->with('persons')->get();

correct: this return just the authenticated user with his persons

Auth::user()->persons()->get()

Model

 public function persons(){
        return $this->hasMany('App\Person', 'user_id');
    }

where is the difference? why first line returns ALL users?

thanks

with is supposed to be called on a Builder object non on a Model instance.

In the first example, you're calling it on a User instance, that is like calling:

User::with('persons')->get();

so Laravel returns all users along with their persons

Note that if you want to load a relation on a single model you can do:

$me = Auth::user();
$me->load('persons');

The use of ->with() in query builder is to eager load the relation so it loads related models. It does not return the related models, only loads them.

One interesting thing to note here is that auth()->user(), return User model instance. Hence, when chaining it with ->with('persons')->get() you're essentially creating a new Query Builder.

$user = auth()->user();
// The following line creates new Query for User model
$allUsersWithPersons = $user->with('persons')->get();
// same as following line
$allUsersWithPersons2 = User::with('persons')->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM