skip to Main Content

Hello Please I am trying to view the records of a user based on the user id I used as a foreign key in another table in laravel. Basically I want the name of the userID to show.

This is my Controller

    public function index()
    {
       
        
        $id = User::all();
        $organisedTrips = organisedTrip::where('userID', '=', $id)->get();
    
        $organisedTrips = organisedTrip::paginate(4);
        return view('welcome', compact('organisedTrips'));
        
    }

The user table

The table where I made the userID a foreign key from the user's table

2

Answers


  1. User::all() returns array of the users. Consider using pluck function and correct your code.

    public function index()
        {
           
            
            $id = User::all()->pluck('id');
            $organisedTrips = organisedTrip::whereIn('userID', $id)->get();
        
            $organisedTrips = organisedTrip::paginate(4);
            return view('welcome', compact('organisedTrips'));
            
        }
    

    Tip:

    It can be done in better way using eloquent.

    Login or Signup to reply.
  2. You can use auth() because this is the simplest and safest way
    enter image description here

    Or you can separate model and controller
    enter image description here

    enter image description here

    I tried this before and it worked.

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