scope in laravel code example
Example 1: laravel create model
php artisan make:model Flight
php artisan make:model Flight --migration
php artisan make:model Flight -m
Example 2: fresh laravel
$flight = Flight::where('number', 'FR 900')->first();
$flight->number = 'FR 456';
$flight->refresh();
$flight->number;
Example 3: laravel scope relationship
class User extends Model {
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
public function scopeWomen($query)
{
return $query->whereGender('W');
}
}
Example 4: model observer laravel
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
protected $fillable = ['title', 'slug', 'content'];
protected static function boot()
{
parent::boot();
static::saving(function ($model) {
$model->slug = str_slug($model->title);
});
}
}
Example 5: laravel create on model
$user = User::create([
'first_name' => 'Taylor',
'last_name' => 'Otwell',
'title' => 'Developer',
]);
$user->title = 'Painter';
$user->isDirty();
$user->isDirty('title');
$user->isDirty('first_name');
$user->isClean();
$user->isClean('title');
$user->isClean('first_name');
$user->save();
$user->isDirty();
$user->isClean();
Example 6: laravel update
<!-mass update-->
App\Models\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);