Saturday, 29 April 2023

Laravel model local scope

Introduction

Laravel is a powerful PHP framework that simplifies web application development, and one of its standout features is the eloquent ORM (Object-Relational Mapping) for database interactions.

Among the many features Eloquent provides, one that stands out for its versatility and readability is the "Local Scope."

In this blog post, we'll delve into the world of Laravel Model Local Scopes, explore their benefits, and provide practical examples of how to use them effectively.


"why it is used local scope"


=> we are working model query like get todays records, get active records, 

  get banned users etc.

  

=> At this time we always use where condition everywhere on controller file. 


=> i think where condition is right it is not wrong, but you have to write if 

    again and again it bad idea

    

=> If you create laravel model eloquent scope then you don't have to write 

   same logic with where condition again and again.


=> " 1) Create Scope in Model "


  here we will use that scope in laravel model file 

  app/Post.php

  


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public $table = "posts";
protected $fillable = [
'id', 'title', 'body', 'status'

];
public function scopeToday($query)
{
return$query->whereDate('created_at', \Carbon\Carbon::today());
}

}


=> fetch all today post query



    Post::select("*")->today()->get();


=> " Dynamic Scope in Model "


we query in controller then we will use that scope in 

app/Post.php


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{

public $table = "posts";

protected $fillable = [
'id', 'title', 'body', 'status'
];

public function scopeStatus($query, $type)
{
return $query->where('status', $type);
}
}


=> "Use Scope Query "

Post::select("*")->status(1)->get();







Conclusion

In this comprehensive guide, we've explored Laravel Model Local Scopes from their fundamentals to advanced techniques. Armed with this knowledge, you'll be better equipped to write cleaner, more maintainable Eloquent queries in your Laravel applications.


No comments:

Post a Comment

Other post

1) The create() Method The  create()  method is a powerful and convenient way to store data in your Laravel application. It is typically use...