Search code examples
phplaravel-5.4laravel-bladeeloquentuserid

How do I fetch data based on user id using Laravel 5.4


I have models User and Diares set up with the hasMany and BelongTo relstionship. I'm trying to fetch data from the Diaries table associated with a particular user. I tried auth but it didnt work for me. How can i achieve that and display it in the blade view as well. Here is my current code:

public function index(User $id)
    {
      $user = User::find($id);
    $record =  $user->diary;


      return view('home')->with('record', $record);

    }

The blade file it should display to:

 @foreach ($record as $diary)
    {{ $diary->error }}
      {{ $diary->fix }}
@endforeach

Solution

  • In your index function the $id is not integer - this is a User instance, so you can try use this:

    public function index(User $user)
    {
      $record =  $user->diary;
    
      return view('home')->with('record', $record);
    
    }