How to Use Model Scope in a Relationship in Laravel
In this tutorial, we will see how to use model scope in a relationship in Laravel, let's assume that we have an articles table each article has a published field and we have a scope inside the article model to get only the published articles, now we want to get the published articles of a given user using the relationship.
Create the article model
First, let's create the article model inside we have the scope to get only the published articles.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Article extends Model
{
use HasFactory;
public function scopePublished($query)
{
return $query->where('published', 1);
}
}
Use the scope inside the relationship
Next, inside the user model, we use the model scope published to get only the published articles of each user.
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password'
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
public function articles() {
return $this->hasMany(Article::class)->published();
}
}