Skip to content
Advertisement

How to get result from database based on the user with laravel

I started coding laravel and everything was fine till I wanted to get the result based on the user, how to do it, what do I need to do?.

Advertisement

Answer

You can use where clause.

Suppose you wanna fetch all the blogs of a user.

like:

Blog::where('user_id', Auth::user()->id)->get();

// Auth::user()->id returns the logged in user's id.

Or

create a relation in User model

AppModelsUser
use AppModelsBlog;

 public function blogs()
 {
     return $this->hasMany(User::class, 'user_id', 'id');
 }

Then

Auth::user()->blogs;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement