laravel eloquent get model with relations

Solutions on MaxInterview for laravel eloquent get model with relations by the best coders in the world

showing results for - "laravel eloquent get model with relations"
Leo
01 Sep 2020
1<?php
2//For example, imagine a blog application in which a User model has many associated Post models:
3namespace App\Models;
4use Illuminate\Database\Eloquent\Model;
5class User extends Model
6{
7    /**
8     * Get all of the posts for the user.
9     */
10    public function posts()
11    {
12        return $this->hasMany(Post::class);
13    }
14}
15
16//You may query the posts relationship and add additional constraints to the relationship like so:
17use App\Models\User;
18$user = User::find(1);
19$user->posts()->where('active', 1)->get();
20