Home > database >  Laravel loop where: Posts as post where post_user_id and and user_id match
Laravel loop where: Posts as post where post_user_id and and user_id match

Time:10-31

as title says I want to make a loop foreach item where the post_user_id and user_id match, but just dont know quite how

@foreach($posts as $post where $post->user_id == auth()->user()->id)

@endforeach

There many posts with different post_user_id's but i want for a specific account to see all his own posts.

CodePudding user response:

You are not supposed to do this logic in your blade file. Rather you should do it in your controller and just pass the variable to the view/blade file.

For example. In your controller:

// I'm assuming the name of your model is POST
$posts = Post::where('user_id',auth()->user()->id)->get();

// this will get all posts where the user_id is equal to the 
// id of the logged in user

return view('THE NAME OF YOUR VIEW FILE GOES HERE', compact('posts'));

Now in your view file you can just loop over this variable as normal:

@foreach($posts as $post)
 ...
@endforeach

CodePudding user response:

$userPosts = Post::where('user_id', auth()->user()->id)->get();

    return view('userPosts',[
        'posts' => $userPosts,
        'categories'=> Category::all()
    ]);

It receives all the data where the user_id and post->user_id matches and everthing works

  • Related