skip to Main Content

I have created a project which allows logged in users to created posts. The post table has a column called post_id. The post_id has the value user id fetched from Session::get('id').

Now I want to fetch all posts associated with a loggedin user by using Post::where('post_id','=',Session::get('id');

Code Below

<?php
namespace AppHttpControllers;

use IlluminateHttpRequest;
//use AppModelsUser;
use AppModelsPost;
use Session;


class PostController extends Controller
{
  public function post(Request $request){
         $posts = Post::where('post_id','=',Session::get('id'));
         return view('dashboard',['posts' => $posts]);
   }
}

in web.php

use AppHttpControllersPostController;

Route::get('/dashaboard',[PostController::class,'post']);

in dashboard view

@foreach ($posts as $post)
                    <tr>
                        <td>{{$post->post_title}}</td>
                        <td>{{$post->post_description}}</td>
                    </tr>
                @endforeach

The error is

Undefined variable $posts

I tried to fetch logged in User’s posts. I want to fetch all posts.

3

Answers


  1. So your setup is a little confusing. Let me break down how you should actually set this up.

    In your User model, you should define a relationship for posts:

    public function posts() {
      return $this->hasMany(Post::class);
    }
    

    In your Post model, you should define a relation for the user:

    public function user() {
      return $this->belongsTo(User::class);
    }
    

    In your posts database table, you’ll want a user_id integer column which will store the post user id.

    Once you’ve done this setup, you’ll be able to get all of the currently logged in users posts like this:

      public function post(Request $request){
             $posts = $request->user()->posts;
             return view('dashboard',['posts' => $posts]);
       }
    
    Login or Signup to reply.
  2. A bit correction to eloquent query that you are using.

    $user_id = Session::get('id');
    
    // change post_id into user_id
    // and add ->get() to fetch all posts related to user_id
    $posts = Post::where('user_id','=', $user_id)->get();
    

    And if the user has way to many posts, for example more than 25.
    You can use pagination

    $perPage = 25;
    $posts = Post::where('user_id','=', $user_id)->paginate($perPage);
    

    https://laravel.com/docs/9.x/pagination#paginating-eloquent-results

    Btw there are other way to get user id as long as this user is logged in

    $user_id = auth()->user()->id;
    $user_id = $request->user()->id;
    $user_id = auth()->id();

    Login or Signup to reply.
  3. For getting logged in user id

    use Auth;
    $user_id = Auth::user()->id;

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search