Query Scope Tutorial in Laravel 11
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
// $post = Post::with("user")->get();
// return $post;
$post = Post::withWhereHas("user", function ($query) {
$query->active();
})->whereStatus(1)->get();
return $post;
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*/
public function show(string $id)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}
Above File is app\Http\Controllers\PostController FileBelow File is app\Http\Controllers\UserController File
<?php
namespace App\Http\Controllers;
use App\Models\Scopes\UserScope;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
// $users = User::with("posts")->active()->sort()->get(); //Here we have used Local Scope
// $users = User::with("posts")->sort()->get(); //Here we have used Global Scope
// $users = User::with("posts")->city(["Goa", "Delhi"])->active()->sort()->get(); //Here we have used Local Scope
// $users = User::with("posts")->city(["Goa"])->sort()->get(); //Here we have used Global Scope
// $users = User::with("posts:title,description,user_id")->city(["Delhi"])->sort()->get(); //Here we have used Global Scope
// $users = User::select("id","name","email")->with("posts:title,description,user_id")->city(["Delhi"])->sort()->get();
// $users = User::city(["Delhi"])->sort()->get(); //Here we have used Global Scope
// $users = User::get(); //Here we have used Global Scope
// $users = User::withoutGlobalScope(UserScope::class)->get(); //Here we have removed Global Scope
$users = User::withoutGlobalScope(UserScope::class)->city(["Delhi"])->sort()->get(); //Here we have removed Global Scope
return $users;
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*/
public function show(string $id)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}
Below File is app\Models\Scopes\UserScope File
<?php
namespace App\Models\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class UserScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*/
public function apply(Builder $builder, Model $model): void
{
$builder->select("id", "name", "email")->with("posts:title,description,user_id")->where("status", 1);
}
}
Below File is app\Models\Post File
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public $timestamps = true;
protected $table = "posts";
protected $fillable = ["title", "description", "status", "user_id"];
public function user()
{
return $this->belongsTo(User::class);
}
}
Below File is app\Models\User File
<?php
namespace App\Models;
use App\Models\Scopes\UserScope;
use Illuminate\Database\Eloquent\Attributes\ScopedBy;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
#[ScopedBy([UserScope::class])] //Second way
class User extends Model
{
public $timestamps = false;
protected $table = "users";
protected $fillable = ["name", "email", "city", "status"];
// First way
protected static function booted(): void
{
static::addGlobalScope("userdetail", function (Builder $builder) {
$builder->where("status", 1);
});
static::addGlobalScope(new UserScope);
}
public function posts()
{
return $this->hasMany(Post::class);
}
public function scopeActive($query)
{
return $query->where("status", 1);
}
public function scopeCity($query, $cityName)
{
return $query->whereIn("city", $cityName);
}
public function scopeSort($query)
{
return $query->orderBy("name", "asc");
}
}
Below File is database\json\posts File
[
{
"title": "News Title One",
"description": "Duis aute irure dolor in reprehenderit in voluptate velit",
"user_id": 1
},
{
"title": "News Title Two",
"description": "Duis aute irure dolor in reprehenderit in voluptate velit",
"user_id": 2
},
{
"title": "News Title Three",
"description": "Duis aute irure dolor in reprehenderit in voluptate velit",
"user_id": 1
},
{
"title": "News Title Four",
"description": "Duis aute irure dolor in reprehenderit in voluptate velit",
"user_id": 3
},
{
"title": "News Title Five",
"description": "Duis aute irure dolor in reprehenderit in voluptate velit",
"user_id": 3
},
{
"title": "News Title Six",
"description": "Duis aute irure dolor in reprehenderit in voluptate velit",
"user_id": 1
},
{
"title": "News Title Seven",
"description": "Duis aute irure dolor in reprehenderit in voluptate velit",
"user_id": 3
},
{
"title": "News Title Eight",
"description": "Duis aute irure dolor in reprehenderit in voluptate velit",
"user_id": 2
},
{
"title": "News Title Nine",
"description": "Duis aute irure dolor in reprehenderit in voluptate velit",
"user_id": 4
}
]
Below File is database\json\users File
[
{
"name": "Yahoo Baba",
"email": "yahoobaba@gmail.com",
"city": "Delhi",
"status": 1
},
{
"name": "Salman Khan",
"email": "salman@gmail.com",
"city": "Mumbai",
"status": 0
},
{
"name": "Deepika Padukone",
"email": "deepika@gmail.com",
"city": "Delhi",
"status": 1
},
{
"name": "Abhishek Bachchan",
"email": "abhishek@gmail.com",
"city": "Goa",
"status": 1
}
]
Below File is database\migrations\2024_12_18_073440_create_users_table File
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string("name");
$table->string("email", 50)->unique();
$table->string("city");
$table->tinyInteger("status")->default(1);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};
Below File is database\migrations\2024_12_18_073726_create_posts_table File
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string("title", 50);
$table->longText("description");
$table->tinyInteger("status")->default(1);
$table->unsignedBigInteger("user_id");
$table->foreign("user_id")->references("id")->on("users")->onUpdate("cascade")->onDelete("cascade");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('posts');
}
};
Below File is database\seeders\DatabaseSeeder File
<?php
namespace Database\Seeders;
use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
// User::factory(10)->create();
// User::factory()->create([
// 'name' => 'Test User',
// 'email' => 'test@example.com',
// ]);
$this->call([
UserSeeder::class,
PostSeeder::class
]);
}
}
Below File is database\seeders\PostSeeder File
<?php
namespace Database\Seeders;
use App\Models\Post;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;
class PostSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$json = File::get(path: "database/json/posts.json");
$posts = collect(json_decode($json));
$posts->each(function ($post) {
Post::create([
"title" => $post->title,
"description" => $post->description,
"user_id" => $post->user_id
]);
});
}
}
Below File is database\seeders\UserSeeder File
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$json = File::get(path: "database/json/users.json");
$users = collect(json_decode($json));
$users->each(function ($user) {
User::create([
"name" => $user->name,
"email" => $user->email,
"city" => $user->city,
"status" => $user->status
]);
});
}
}
Below File is routes\web File
.png)
.png)
.png)
.png)
.png)
Comments
Post a Comment