6.5.3. How Laravel Manages Data

Now let us talk a bit about how to work in Laravel with models for retrieving, inserting, updating and deleting data. Laravel uses the query constructor to manage data. The full description of the syntax and capabilities of this constructor is available at https://laravel.com/docs/5.2/queries. For example, you can execute the following query to retrieve all supplier rows:

  1. $customers = DB::table('CUSTOMER')->get();

This query constructor is quite a powerful tool for building and executing SQL queries. You can also direct it to filter, sort and merge tables. For example:

  1. DB::table('users')
  2. ->join('contacts', function ($join) {
  3. $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
  4. })
  5. ->get()

Nevertheless, models are more convenient to work with. You can find the description of Eloquent ORM models and the syntax for querying them at https://laravel.com/docs/5.2/eloquent.

As an example, to retrieve all elements from the collection of customers would require executing the following query:

  1. $customers = Customer::all();

This query will return the first 20 customers sorted alphabetically:

  1. $customers = App\Customer::select()
  2. ->orderBy('name')
  3. ->take(20)
  4. ->get();

Complex Models

When a model is more complex, its relationships or relationship collections can be retrieved via dynamic attributes. The following query, for example, returns the items of the invoice that has the identifier 1:

  1. $lines = Invoice::find(1)->lines;

Records are added by creating an instance of the model, initiating its attributes and saving the model using the save method:

  1. $flight = new Flight;
  2. $flight->name = $request->name;
  3. $flight->save();

Updating a record involves finding it, accepting changes to the appropriate attributes and saving it with the save method:

  1. $flight = App\Flight::find(1);
  2. $flight->name = 'New Flight Name';
  3. $flight->save();
  4. To delete a record, involves finding it and calling the delete method.
  5. $flight = App\Flight::find(1);
  6. $flight->delete();

The destroy method allows a record to be deleted more rapidly by its key value, without needing to retrieve its instance:

  1. App\Flight::destroy(1);

There are other ways of deleting records, for instance, “soft” deletion. You can read more about deletion methods at https://laravel.com/docs/5.2/eloquent#deleting-models.