Laravel 5.1

Session 6

Muhammad Rizwan Arshad,

Principal Software Engineer, Nextbridge.

August 04, 2015.

Eloquent: Getting Started

Introduction

ActiveRecord implementation for working with your database.

Each database table has a corresponding "Model"

 

Configure a database connection in config/database.php

 

Defining Models

Models typically live in the app directory

Place anywhere that can be auto-loaded by composer.json

All Eloquent models extend Illuminate\Database\Eloquent\Model class.

 

To create a Model:

#php artisan make:model User

 

To generate migration at the same time:

php artisan make:model User --migration
php artisan make:model User -m

Table Names

 The "snake case", plural name of the class will be used as the table name

namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
    /**
     * The table associated with the model.
     * @var string
     */
    protected $table = 'my_flights';
}

Primary Keys

Eloquent will also assume that each table has a primary key column named id. 

You may define a $primaryKey property to override this convention.

Timestamps

namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;
    protected $dateFormat = 'U';

}

Retrieving Multiple Models

Retrieving Multiple Models

namespace App\Http\Controllers;
use App\Flight;
use App\Http\Controllers\Controller;
class FlightController extends Controller
{
    /**
     * Show a list of all available flights.
     * @return Response
     */
    public function index()
    {
        $flights = Flight::all();
        return view('flight.index', ['flights' => $flights]);
    }
}

Accessing Column Values

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

Adding Additional Constraints

$flights = App\Flight::where('active', 1)
               ->orderBy('name', 'desc')
               ->take(10)
               ->get();

Collections

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

Chunking Results

Flight::chunk(200, function ($flights) {
    foreach ($flights as $flight) {
        //
    }
});

Retrieving Single Models / Aggregates

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();

Not Found Exceptions

$model = App\Flight::findOrFail(1);

$model = App\Flight::where('legs', '>', 100)->firstOrFail();

Retrieving Aggregates

$count = App\Flight::where('active', 1)->count();

$max = App\Flight::where('active', 1)->max('price');

Inserting & Updating Models

Basic Inserts

namespace App\Http\Controllers;
use App\Flight;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class FlightController extends Controller
{
    public function store(Request $request)
    {
        $flight = new Flight;
        $flight->name = $request->name;
        $flight->save();
    }
}

Basic 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

namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
    protected $fillable = ['name'];
    protected $guarded = ['price'];
}

Other Creation Methods

/* Retrieve the flight by the attributes, or create it if it doesn't exist... */

$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);

/* Retrieve the flight by the attributes, or instantiate a new instance... */

$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);

Deleting Models

Deleting Models

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

 

Deleting An Existing Model By Key

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

 

Deleting Models By Query

$deletedRows = App\Flight::where('active', 0)->delete();

Soft Deleting

namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Flight extends Model
{
    use SoftDeletes;
    /**
     * The attributes that should be mutated to dates.
     * @var array
     */
    protected $dates = ['deleted_at'];
}

Including Soft Deleted Models

$flights = App\Flight::withTrashed()
                ->where('account_id', 1)
                ->get();

$flight->history()->withTrashed()->get();

Retrieving Only Soft Deleted Models

$flights = App\Flight::onlyTrashed()
                ->where('airline_id', 1)
                ->get();

Restoring / Removing

$flight->restore();

 

App\Flight::withTrashed()
        ->where('airline_id', 1)
        ->restore();

 

$flight->history()->restore();

 

// Force deleting a single model instance...
$flight->forceDelete();

// Force deleting all related models...
$flight->history()->forceDelete();

Query Scopes

Query Scopes

class User extends Model
{
    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }
    public function scopeActive($query)
    {
        return $query->where('active', 1);
    }
}
$users = App\User::popular()->active()
                            ->orderBy('created_at')
                            ->get();

Dynamic Scopes

class User extends Model
{
    public function scopeOfType($query, $type)
    {
        return $query->where('type', $type);
    }
}

 

Now, you may pass the parameters when calling the scope:

$users = App\User::ofType('admin')->get();

Good Day !

Laravel 5.1 - Session 06

By gr8rizwan

Laravel 5.1 - Session 06

  • 1,245