Skip to content
Advertisement

Laravel – Fetch data from other table column from linked key column

I have 2 tables. (1) being users, and (2) being foods.

In the [users] table, there is a food_id bracket that is linked as a foreign key to an item/column’s id in the other table [foods]. I want to be able to go fetch data in that other column, via my user_id link in my [users] table.

I don’t know how I am supposed to do this, despite reading the documentation, I am very beginner at this and it is part of my assignment. I’ve tried a few possible solutions, only to fail.

I have a controller, in which I refer the function into a view, that will display the food item/column related to the current logged user, with an if statement verifying if a certain data is present in order to display the HTML block object.

public function browseReserved()
    {
        //
        
        $user = User::find(auth()->user());
        $foodId = $user->where('food_id')->id;
    }

So, how do I go fetch data from an item located in another table, from a data key that is linked to the id of said item?

Advertisement

Answer

add relationship in user model

public function food(){

  return $this->belongsTo(Food::class);
}

then in controller

public function browseReserved()
{
   $user = User::with('food')->find(auth()->id());
  
  dd($user->food);
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement