Laravel Eloquent

Laravel Eloquent

Provides a beautiful, simple ActiveRecord implementation for working with your database.

Eloquent Events

Allow you to easily execute code each time a specific model class is saved or updated in the database.

<?php

namespace App;

use App\Events\UserSaved;
use App\Events\UserDeleted;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The event map for the model.
     *
     * @var array
     */
    protected $dispatchesEvents = [
        'saved' => UserSaved::class,
        'deleted' => UserDeleted::class,
    ];
}

Defining Models

Php artisan make:model Flight
Php artisan make:model Flight --migration

php artisan make:model Flight -m

Typically live in the app directory, but you are free to place them anywhere.

Retrieving Models

<?php

$flights = App\Flight::all();

foreach ($flights as $flight) {
    echo $flight->name;
}

Retrieving Single Models / Aggregates

// Retrieve a model by its primary key...
$flight = App\Flight::find(1);

// Retrieve the first model matching the query constraints...
$flight = App\Flight::where('active', 1)->first();
$flights = App\Flight::find([1, 2, 3]);

Inserting & Updating Models

Deleting Models

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

$flight->delete();

Query Scopes

Comparing Models

If ($post->is($anotherPost)) {
    //
}

Laravel Eloquent — Structure map

Clickable & Draggable!

Laravel Eloquent — Related pages: