laravel global scopes code example
Example 1: laravel create or update
$flight = App\Models\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99, 'discounted' => 1]
);
Example 2: larave Soft Deletes
Schema::table('flights', function (Blueprint $table) {
$table->softDeletes();
});
Example 3: laravel scope
public function apply(Builder $builder, Model $model)
{
$builder->where('age', '>', 200);
}
Example 4: laravel model::query
Model::where()->get();
Model::query()->where()->get();
Model::query();
Example 5: laravel global scope
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class AncientScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$builder->where('created_at', '<', now()->subYears(2000));
}
}