User Tools

Site Tools


Sidebar

Dan's Wiki

DokuWiki Instructions (local) DokuWiki Manual
Site Checker (Orphans Wanted)

Edit Sidebar

laravel:eloquent

This is an old revision of the document!


(Laravel) Eloquent Notes

Inserting New Row

To create a new record in the database, simply create a new model instance, set attributes on the model, then call the save method:

  $flight = new Flight;
  $flight->name = $request->name;
  $flight->save();

Update Row

he save method may also be used to update models that already exist in the database. To update a model, you should retrieve it, set any attributes you wish to update, and then call the save method. Again, the updated_at timestamp will automatically be updated, so there is no need to manually set its value:

  $flight = App\Flight::find(1);
  $flight->name = 'New Flight Name';
  $flight->save();

Mass Updates

There are means to update database columns or models. See https://laravel.com/docs/5.3/eloquent

Delete Row

If you have the model

To delete a model, call the delete method on a model instance:

  $flight = App\Flight::find(1);
  $flight->delete();

If you have the model's key

In the example above, we are retrieving the model from the database before calling the delete method. However, if you know the primary key of the model, you may delete the model without retrieving it. To do so, call the destroy method:

  App\Flight::destroy(1);
  App\Flight::destroy([1, 2, 3]);
  App\Flight::destroy(1, 2, 3);

Deleting Models By Query

Of course, you may also run a delete statement on a set of models. In this example, we will delete all flights that are marked as inactive. Like mass updates, mass deletes will not fire any model events for the models that are deleted:

  $deletedRows = App\Flight::where('active', 0)->delete();
laravel/eloquent.1482370096.txt.gz · Last modified: 2016/12/22 01:28 by dwheele