10 Advanced features of Laravel Eloquent
Eager loading allows us to retrieve all related models in a single query, which can help to minimize the number of unnecessary database queries. We can also apply constraints to the eager loading to filter the results further.
$users = User::with(['posts' => function ($query) {
? ? $query->where('published', '=', true);
}])->get();
2. Querying Relationship Existence
In some cases, you may want to retrieve records that have a related model or not. The has and doesntHave methods are useful for querying relationship existence.
$posts = Post::has('comments')->get(); // retrieve posts with at least one comment
$posts = Post::doesntHave('comments')->get(); // retrieve posts with no comment
3. Polymorphic Relationships
Polymorphic relationships allow us to associate a model with multiple models on a single association. This can be useful when we have multiple models that need to relate to each other.
class Comment extends Model
{
? ? public function commentable()
? ? {
? ? ? ? return $this->morphTo();
? ? }
}
class Post extends Model
{
? ? public function comments()
? ? {
? ? ? ? return $this->morphMany(Comment::class, 'commentable');
? ? }
}
class Video extends Model
{
? ? public function comments()
? ? {
? ? ? ? return $this->morphMany(Comment::class, 'commentable');
? ? }
}
4. Global Scopes
Global scopes allow us to automatically apply filters to Eloquent queries. For example, we can use a global scope to exclude soft-deleted records from all queries by default.
class SoftDeletingScope implements Scope
{
? ? public function apply(Builder $builder, Model $model)
? ? {
? ? ? ? $builder->whereNull($model->getQualifiedDeletedAtColumn());
? ? }
? ? public function extend(Builder $builder)
? ? {
? ? ? ? $builder->macro('withTrashed', function (Builder $builder) {
? ? ? ? ? ? return $builder->withoutGlobalScope($this)->orWhereNotNull('deleted_at');
? ? ? ? });
? ? }
}
class Post extends Model
{
? ? protected static function boot()
? ? {
? ? ? ? parent::boot();
? ? ? ? static::addGlobalScope(new SoftDeletingScope);
? ? }
}
5. Model Observers
Model observers allow us to listen for specific events on Eloquent models, such as creating or updating a record. This can be useful for triggering other actions, such as sending an email or updating another model.
class PostObserver
{
? ? public function created(Post $post)
? ? {
? ? ? ? Mail::to($post->author->email)
? ? ? ? ? ? ->send(new NewPostNotification($post));
? ? }
}
class Post extends Model
{
? ? protected static function boot()
? ? {
? ? ? ? parent::boot();
? ? ? ? Post::observe(PostObserver::class);
? ? }
}
6. Global Query Scopes
领英推荐
Global query scopes allow us to modify all queries for a given model. For example, we may want to automatically include certain relationships on all queries.
trait HasAuthor
{
? ? public function scopeWithAuthor($query)
? ? {
? ? ? ? return $query->with('author');
? ? }
}
class Post extends Model
{
? ? use HasAuthor;
}
7. Accessor & Mutator
Accessors allow us to modify attribute values before they are returned, while mutators allow us to modify attribute values before they are saved to the database.
class Post extends Model
{
? ? public function getSlugAttribute()
? ? {
? ? ? ? return Str::slug($this->title);
? ? }
? ? public function setTitleAttribute($value)
? ? {
? ? ? ? $this->attributes['title'] = ucwords($value);
? ? }
}
8. Model Factories
Model Factories allow us to easily create dummy data for testing or seeding the database.
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Factories\Factory;
class Post extends Model
{
? ? use HasFactory;
? ? protected $fillable = ['title', 'content'];
? ? protected static function newFactory()
? ? {
? ? ? ? return PostFactory::new();
? ? }
}
class PostFactory extends Factory
{
? ? protected $model = Post::class;
? ? public function definition()
? ? {
? ? ? ? return [
? ? ? ? ? ? 'title' => $this->faker->sentence,
? ? ? ? ? ? 'content' => $this->faker->paragraph,
? ? ? ? ];
? ? }
}
$post = Post::factory()->create(); // create a new post
$posts = Post::factory(10)->create(); // create 10 new posts
9. Pluck()
The pluck() method allows us to retrieve a single column's value for each record. This can be useful for retrieving a list of IDs or titles for all records.
$titles = Post::pluck('title'); // retrieve an array of post titles
$ids = Post::pluck('id'); // retrieve an array of post IDs
10. Raw Expressions
Sometimes we may need to use raw SQL expressions to achieve a certain result. Eloquent allows us to use raw expressions in queries.
$users = DB::table('users')
? ? ? ? ? ? ->selectRaw('count(*) as user_count, status')
? ? ? ? ? ? ->where('status', '<>', 1)
? ? ? ? ? ? ->groupBy('status')
? ? ? ? ? ? ->get();
Hope you'll find this article useful.
Hello Moji... We post 100's of job opportunities for developers daily here. Candidates can talk to HRs directly. Feel free to share it with your network. Visit this link - https://jobs.hulkhire.com And start applying.. Will be happy to address your concerns, if any