start
1. Introduction
2. Define model
php artisan make:model User
php artisan make:model User --migration php artisan make:model User -m
2.1 Eloquent model convention
<? php namespace App; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ // }
2.1.1 Table name
<? php namespace App; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ /** *Data table associated to model * * @var string */ protected $table = 'my_flights'; }
2.1.2 Primary key
id
$primaryKey
2.1.3 Time stamp
<? php namespace App; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ /** *Indicates whether the model should be time stamped * * @var bool */ public $timestamps = false; }
<? php namespace App; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ /** *Storage format of model date column * * @var string */ protected $dateFormat = 'U'; }
3. Get multiple models
<? php namespace App\Http\Controllers; use App\Flight; use App\Http\Controllers\Controller; class FlightController extends Controller{ /** *Display all valid flight lists * * @return Response */ public function index() { $flights = Flight::all(); return view('flight.index', ['flights' => $flights]); } }
3.1 Access Column Values
foreach ($flights as $flight) { echo $flight->name; }
3.2 Add additional constraints
$flights = App\Flight::where('active', 1) ->orderBy('name', 'desc') ->take(10) ->get();
Note: Since the Eloquent model is essentially a query builder, you can use all the methods of the query builder in Eloquent queries.
3.3 Collection
foreach ($flights as $flight) { echo $flight->name; }
3.4 Blocking result set
Flight::chunk(200, function ($flights) { foreach ($flights as $flight) { // } });
4. Get single model/aggregation
//Get model through primary key $flight = App\Flight::find(1); //Get the first model matching the query criteria $flight = App\Flight::where('active', 1)->first();
$model = App\Flight::findOrFail(1); $model = App\Flight::where('legs', '>', 100)->firstOrFail();
Route::get('/api/flights/{id}', function ($id) { return App\Flight::findOrFail($id); });
4.1 Obtaining Aggregation
$count = App\Flight::where('active', 1)->count(); $max = App\Flight::where('active', 1)->max('price');
Extended reading: Example Tutorial - ORM Overview, Model Definition and Basic Query
5. Insert/Update Model
5.1 Basic insertion
<? php namespace App\Http\Controllers; use App\Flight; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class FlightController extends Controller{ /** *Create a new flight instance * * @param Request $request * @return Response */ public function store(Request $request) { // Validate the request... $flight = new Flight; $flight->name = $request->name; $flight->save(); } }
5.2 Basic update
$flight = App\Flight::find(1); $flight->name = 'New Flight Name'; $flight->save();
App\Flight::where('active', 1) ->where('destination', 'San Diego') ->update(['delayed' => 1]);
5.3 Batch assignment
<? php namespace App; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ /** *Attributes that can be assigned in batch * * @var array */ protected $fillable = ['name']; }
$flight = App\Flight::create(['name' => 'Flight 10']);
<? php namespace App; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ /** *Attributes that cannot be assigned in batch * * @var array */ protected $guarded = ['price']; }
5.3.1 Other creation methods
//Get the flight through the attribute. If it does not exist, create it $flight = App\Flight::firstOrCreate(['name' => 'Flight 10']); //Get the flight through the attribute. If it does not exist, initialize a new instance $flight = App\Flight::firstOrNew(['name' => 'Flight 10']);
Extended reading: Example tutorial - model creation, update and batch assignment
6. Delete Model
$flight = App\Flight::find(1); $flight->delete();
6.1 Deleting a Model by Primary Key
App\Flight::destroy(1); App\Flight::destroy([1, 2, 3]); App\Flight::destroy(1, 2, 3);
6.2 Delete model through query
$deletedRows = App\Flight::where('active', 0)->delete();
6.3 Soft deletion
<? php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Flight extends Model{ use SoftDeletes; /** *The attribute should be adjusted to date * * @var array */ protected $dates = ['deleted_at']; }
Schema::table('flights', function ($table) { $table->softDeletes(); });
if ($flight->trashed()) { // }
6.4 Querying Soft Deleted Models
6.4.1 Include Soft Delete Model
$flights = App\Flight::withTrashed() ->where('account_id', 1) ->get();
$flight->history()->withTrashed()->get();
6.4.2 Get Soft Delete Models Only
$flights = App\Flight::onlyTrashed() ->where('airline_id', 1) ->get();
6.4.3 Restore Soft Delete Model
$flight->restore();
App\Flight::withTrashed() ->where('airline_id', 1) ->restore();
$flight->history()->restore();
6.4.4 Permanently Delete Model
//Force deletion of a single model instance $flight->forceDelete(); //Force deletion of all associated models $flight->history()->forceDelete();
Extended reading: Example Tutorial - Implementation of Model Deletion and Soft Deletion
7. Query Scope
<? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model{ /** *Query scope containing only active users * * @return \Illuminate\Database\Eloquent\Builder */ public function scopePopular($query) { return $query->where('votes', '>', 100); } /** *Only include the query scope of the active user * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeActive($query) { return $query->where('active', 1); } }
7.1 Using Query Scope
$users = App\User::popular()->women()->orderBy('created_at')->get();
7.2 Dynamic Scope
<? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model{ /** *Only query scope for users of type * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeOfType($query, $type) { return $query->where('type', $type); } }
$users = App\User::ofType('admin')->get();
8. Events
creating
created
updating
updated
saving
saved
deleting
deleted
restoring
restored
8.1 Basic use
<? php namespace App\Providers; use App\User; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider{ /** *Start all application services * * @return void */ public function boot() { User::creating(function ($user) { if ( ! $ user->isValid()) { return false; } }); } /** *Registered Service Provider * * @return void */ public function register() { // } }
Extended reading: Example Tutorial - Eloquent Query Scope and Model Events