Search code examples
laravelfilterviewfetch

How to retrieve and display Eloquent relationships in Laravel


What I'm trying to accomplish:

Retrieve all App\Post models related to the authenticated user and display them in the view.


Errors I'm receiving:

Undefined variable: and Property [id] does not exist on this collection instance when clicking on the <a name="posts"> tag.


What I've been trying:

PagesController :

 public function show($id) {
    $user = User::find($id);
    return view('pages.index', compact('user'));
}

Index :

@extends('layouts.app')

@section('content')
    <h1>Welcome to notesite!</h1>
    
        <a href="/notes/show/{{ Auth::user()->id }}" name="posts">Show your posts</a>

    
@endsection

Routes :

Route::get('/', function () {
    return view('welcome');
});
Route::get('/pages/index', 'PagesController@index');
Route::get('/pages/about', 'PagesController@about');
Route::get('/pages/services', 'PagesController@services');

Route::get('/notes/index', 'NotesController@index');
Route::get('/notes/show/{user}', 'NotesController@show');
Auth::routes();
    
Route::get('/home', 'HomeController@index')->name('home');

Can anyone provide a solution?


Solution

  • Welcome to SO!

    I'd recommend you reading up on Eloquent relationships, especially the part about eager loading if you plan on dealing with a lot of records.

    You could do something like the following:

    User Model

    // Add this bit to your existing model to define the relationship 
    // ( assuming that 1 user can have many different posts )
    
    public function posts() {
        return $this->hasMany('App\Post');
    }
    

    Post Model

    // By default, Eloquent will automatically determine the proper foreign key column,
    // noted here as user_id
    
    protected $fillable = ['title', 'body', 'user_id'];
    

    PostController

    public function show() {
        $posts = App\User::find(Auth::id())->posts; // Fetch the authenticated users posts
    
        return view('show-posts', compact('posts') ); // Pass them back to the view
    }
    

    routes/web.php

    Route::view('/pages/index', 'index');
    Route::get('/posts/show', 'PostController@show');
    

    index.blade.php

    <a href="/posts/show">Show user-specific posts!</a>
    

    show-posts.blade.php

    @foreach( $posts as $post )
        {{ $post->body }}
    @endforeach