skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER
    $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 everything works.


  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search