Eloquent One to Many Relationship

Update your Post model by adding this:

    public function posts(){
        return $this->hasMany('App\Models\Post');
    }

We can now display the user’s post titles in our routes:

use App\Models\User;

/*
|--------------------------------------------------------------------------
| ELOQUENT Relationships
|--------------------------------------------------------------------------
*/

Route::get('/posts', function(){
    $user = User::find(1);
    foreach($user->posts as $post){
        echo $post->title.'<br>';
    }
});

View in your browser.

Leave a Reply

Your email address will not be published.