Learn How to Use Laravel Global Scope Closure

Laravel global scopes closure allows us to implement specific actions over a model that will be called every time the model gets called. Using global scope can make sure our model is scoped within any type of logic that we set. For example this sample below we will scope a product base on admin_id so this product model will show based on the admin it belongs to. Note: This sample is a demonstration only. It does not represent a real application use case.

In Laravel API route (api.php)

Create sample API to call product list

<?php

use App\Http\Controllers\ProductController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::get('product', [ ProductController::class, 'index' ]);

In ProductController.php

Getting a list of product

<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        return Product::get();
    }
}

In the Product.php model

In the static booted function is where you can define scope closures

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class Product extends Model
{
    protected $fillable = [
        'name',
        'description',
        'admin_id'
    ];

    protected static function booted()
    {
        static::addGlobalScope('byUser', function (Builder $builder) {
            $builder->where('admin_id', Auth::id());
        });
    }
}

After that, you will get the product that belongs to authenticated admin.

Product DB

Result