php artisan make:model Flight --migration
php artisan make:model Flight -m
protected $table = 'my_flights';
protected $primaryKey = 'flight_id';
public $incrementing = false;
protected $keyType = 'string';
By default, Eloquent expects created_at and updated_at columns to exist on your tables.
public $timestamps = false;
If you need to customize the format of your timestamps, set the $dateFormat property on your model. This property determines how date attributes are stored in the database
protected $dateFormat = 'U';
const CREATED_AT = 'creation_date';
const UPDATED_AT = 'last_update';
Default Attribute Values
protected $attributes = ['delayed' => false,
];
App\Flight::all();
$flights = App\Flight::find([1, 2, 3]);
$flights = App\Flight::where('active', 1)
->orderBy('name', 'desc')
->take(10)
->get();
$flight = App\Flight::where('active', 1)->first();
Not Found Exceptions
$model = App\Flight::findOrFail(1);$model = App\Flight::where('legs', '>', 100)->firstOrFail();
If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods
Retrieving Aggregates
You may also use the count, sum, max, and other aggregate methods provided by the query builder. These methods return the appropriate scalar value instead of a full model instance:$count = App\Flight::where('active', 1)->count();
$max = App\Flight::where('active', 1)->max('price');
Inserts
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
$flight->name = $request->name;
$flight->save();
Updates
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
Mass Assignment
You may also use the create method to save a new model in a single line. before doing so, you will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment by default.
protected $fillable = ['name'];
$flight = App\Flight::create(['name' => 'Flight 10']);
If you already have a model instance, you may use the fill method to populate it with an array of attributes:
$flight->fill(['name' => 'Flight 22']);
protected $guarded = ['price'];
protected $guarded = [];
you should use either $fillable or $guarded - not both.
Deleting Models
$flight = App\Flight::find(1);
$flight->delete();
App\Flight::destroy(1);
App\Flight::destroy(1, 2, 3);
App\Flight::destroy([1, 2, 3]);
App\Flight::destroy(collect([1, 2, 3]));
$deletedRows = App\Flight::where('active', 0)->delete();