quick get start
Eloquent: getting started
-
brief introduction -
Model definition -
Model retrieval -
Retrieving a single model/collection -
Insert&Update Model -
Delete Model -
Model Copy -
Query Scope -
Model comparison -
event
brief introduction
Model definition
php artisan make : model Flight
php artisan make : model Flight -- migration php artisan make : model Flight - m
php artisan make : model Flight -- factory php artisan make : model Flight - f php artisan make : model Flight -- seed php artisan make : model Flight - s php artisan make : model Flight -- controller php artisan make : model Flight - c php artisan make : model Flight - mfsc
Eloquent model convention
< ? php namespace App\Models ; use Illuminate\Database\Eloquent\Model ;
class Flight extends Model
{
//
}
Datasheet Name
< ? php namespace App\Models ; use Illuminate\Database\Eloquent\Model ;
class Flight extends Model
{
/** *Table name associated with the model * * @var string */
protected $table = 'my_flights' ;
}
Primary key
< ? php namespace App\Models ; use Illuminate\Database\Eloquent\Model ;
class Flight extends Model
{
/** *Primary key associated with table * * @var string */
protected $primaryKey = 'flight_id' ;
}
< ? php class Flight extends Model
{
/** *Whether the primary key is incremented actively * * @var bool */
public $incrementing = false ;
}
< ? php class Flight extends Model
{
/** *Automatically increment the Primary Key Type * * @var string */
protected $keyType = 'string' ;
}
time stamp
< ? php namespace App\Models ; use Illuminate\Database\Eloquent\Model ;
class Flight extends Model
{
/** *Whether to actively maintain the timestamp * * @var bool */
public $timestamps = false ;
}
< ? php namespace App\Models ; use Illuminate\Database\Eloquent\Model ;
class Flight extends Model
{
/** *Storage format of model date * * @var string */
protected $dateFormat = 'U' ;
}
< ? php class Flight extends Model
{
const CREATED_AT = 'creation_date' ;
const UPDATED_AT = 'last_update' ;
}
Database connection
< ? php namespace App\Models ; use Illuminate\Database\Eloquent\Model ;
class Flight extends Model
{
/** *Database connection name of the model * * @var string */
protected $connection = 'connection-name' ;
}
Default attribute value
< ? php namespace App\Models ; use Illuminate\Database\Eloquent\Model ;
class Flight extends Model
{
/** *Default values for model properties * * @var array */
protected $attributes = [
'delayed' => false ,
] ;
}
Model retrieval
< ? php $flights = App\Models\Flight : : all ( ) ;
foreach ( $flights as $flight ) { echo $flight - > name ;
}
Additional constraint
$flights = App\Models\Flight : : where ( 'active' , one )
- > orderBy ( 'name' , 'desc' )
- > take ( ten )
- > get ( ) ;
Tip: Since Eloquent model is also a query constructor, you should also read Query Builder All available methods. You can use these methods in Eloquent queries.
Reload model
$flight = App\Models\Flight : : where ( 'number' , 'FR 900' ) - > first ( ) ; $freshFlight = $flight - > fresh ( ) ;
$flight = App\Models\Flight : : where ( 'number' , 'FR 900' ) - > first ( ) ; $flight - > number = 'FR 456' ; $flight - > refresh ( ) ; $flight - > number ; // "FR 900"
aggregate
$flights = $flights - > reject ( function ( $flight ) {
return $flight - > cancelled ;
} ) ;
foreach ( $flights as $flight ) { echo $flight - > name ;
}
Result blocking
Flight : : chunk ( two hundred , function ( $flights ) {
foreach ( $flights as $flight ) {
//
}
} ) ;
Flight : : where ( 'departed' , true ) - > chunkById ( two hundred , function ( $flights ) { $flights - > each - > update ( [ 'departed' => false ] ) ;
} ) ;
Use Cursor
foreach ( Flight : : where ( 'foo' , 'bar' ) - > cursor ( ) as $flight ) {
//
}
$users = App\Models\User : : cursor ( ) - > filter ( function ( $user ) {
return $user - > id > five hundred ;
} ) ;
foreach ( $users as $user ) { echo $user - > id ;
}
Advanced Subquery
Select Subquery
use App\Models\Destination ; use App\Models\Flight ;
return Destination : : addSelect ( [ 'last_flight' => Flight : : select ( 'name' )
- > whereColumn ( 'destination_id' , 'destinations.id' )
- > orderBy ( 'arrived_at' , 'desc' )
- > limit ( one )
] ) - > get ( ) ;
Sort by subquery
return Destination : : orderByDesc ( Flight : : select ( 'arrived_at' )
- > whereColumn ( 'destination_id' , 'destinations.id' )
- > orderBy ( 'arrived_at' , 'desc' )
- > limit ( one )
) - > get ( ) ;
Retrieving a single model/collection
//Find a model by primary key $flight = App\Models\Flight : : find ( one ) ;
//Find the first model matching the query criteria $flight = App\Models\Flight : : where ( 'active' , one ) - > first ( ) ;
//Find the fast implementation of the first model that meets the query criteria $flight = App\Models\Flight : : firstWhere ( 'active' , one ) ;
$flights = App\Models\Flight : : find ( [ one , two , three ] ) ;
$model = App\Models\Flight : : where ( 'legs' , '>' , one hundred ) - > firstOr ( function ( ) {
// ...
} ) ;
$model = App\Models\Flight : : where ( 'legs' , '>' , one hundred )
- > firstOr ( [ 'id' , 'legs' ] , function ( ) {
// ...
} ) ;
Not found exception
$model = App\Models\Flight : : findOrFail ( one ) ; $model = App\Models\Flight : : where ( 'legs' , '>' , one hundred ) - > firstOrFail ( ) ;
Route : : get ( '/api/flights/{id}' , function ( $id ) {
return App\Models\Flight : : findOrFail ( $id ) ;
} ) ;
Retrieve Collection
$count = App\Models\Flight : : where ( 'active' , one ) - > count ( ) ; $max = App\Models\Flight : : where ( 'active' , one ) - > max ( 'price' ) ;
Insert and update models
insert
< ? php namespace App\Http\Controllers ; use App\Http\Controllers\Controller ; use App\Models\Flight ; use Illuminate\Http\Request ;
class FlightController extends Controller
{
/** *Create a new instance * * @param Request $request * @return Response */
public function store ( Request $request )
{
//Verify request $flight = new Flight ; $flight - > name = $request - > name ; $flight - > save ( ) ;
}
}
to update
$flight = App\Models\Flight : : find ( one ) ; $flight - > name = 'New Flight Name' ; $flight - > save ( ) ;
Batch update
App\Models\Flight : : where ( 'active' , one )
- > where ( 'destination' , 'San Diego' )
- > update ( [ 'delayed' => one ] ) ;
Note: When batch updating through Eloquent, the updated model will not be triggered
saving ,
saved ,
updating and
updated Model events. This is because the model is never actually retrieved during a batch update.
Check attribute changes
$user = User : : create ( [
'first_name' => 'Taylor' ,
'last_name' => 'Otwell' ,
'title' => 'Developer' ,
] ) ; $user - > title = 'Painter' ; $user - > isDirty ( ) ; // true $user - > isDirty ( 'title' ) ; // true $user - > isDirty ( 'first_name' ) ; // false $user - > isClean ( ) ; // false $user - > isClean ( 'title' ) ; // false $user - > isClean ( 'first_name' ) ; // true $user - > save ( ) ; $user - > isDirty ( ) ; // false $user - > isClean ( ) ; // true
$user = User : : create ( [
'first_name' => 'Taylor' ,
'last_name' => 'Otwell' ,
'title' => 'Developer' ,
] ) ; $user - > title = 'Painter' ; $user - > save ( ) ; $user - > wasChanged ( ) ; // true $user - > wasChanged ( 'title' ) ; // true $user - > wasChanged ( 'first_name' ) ; // false
$user = User : : find ( one ) ; $user - > name ; // John $user - > email ; // john@example.com $user - > name = "Jack" ; $user - > name ; // Jack $user - > getOriginal ( 'name' ) ; // John $user - > getOriginal ( ) ; //Original attribute array
Batch assignment
< ? php namespace App\Models ; use Illuminate\Database\Eloquent\Model ;
class Flight extends Model
{
/** *Batch assignable attribute * * @var array */
protected $fillable = [ 'name' ] ;
}
$flight = App\Models\Flight : : create ( [ 'name' => 'Flight 10' ] ) ;
$flight - > fill ( [ 'name' => 'Flight 22' ] ) ;
Batch assignment&JSON column
/** *Properties that can be assigned in batches. * * @var array */ $fillable = [
'options->enabled' ,
] ;
Batch assignment allowed
/** *Attributes that cannot be assigned in batches * * @var array */
protected $guarded = [ ] ;
Other creation methods
firstOrCreate
/ firstOrNew
//Retrieve flights by name. If it does not exist, create a new model and insert it into the database $flight = App\Models\Flight : : firstOrCreate ( [ 'name' => 'Flight 10' ] ) ;
//Retrieve flights by name, or create a new model and insert it into the database using the name and delayed attributes and arraval_time attributes $flight = App\Models\Flight : : firstOrCreate (
[ 'name' => 'Flight 10' ] ,
[ 'delayed' => one , 'arrival_time' => '11:30' ]
) ;
//Retrieve the flight by name. If it does not exist, the returned model instance has not been saved to the database $flight = App\Models\Flight : : firstOrNew ( [ 'name' => 'Flight 10' ] ) ;
//The model instance retrieved by name or returned by name and delayed properties and arrival_time properties has not been saved to the database $flight = App\Models\Flight : : firstOrNew (
[ 'name' => 'Flight 10' ] ,
[ 'delayed' => one , 'arrival_time' => '11:30' ]
) ;
updateOrCreate
//If there is a flight from Auckland to San Diego, the price is set at 99 dollars
//If the existing model is not matched, create a $flight = App\Models\Flight : : updateOrCreate (
[ 'departure' => 'Oakland' , 'destination' => 'San Diego' ] ,
[ 'price' => ninety-nine , 'discounted' => one ]
) ;
App\Models\Flight : : upsert ( [
[ 'departure' => 'Oakland' , 'destination' => 'San Diego' , 'price' => ninety-nine ] ,
[ 'departure' => 'Chicago' , 'destination' => 'New York' , 'price' => one hundred and fifty ]
] , [ 'departure' , 'destination' ] , [ 'price' ] ) ;
Note: All databases except SQL Server require
upsert The column in the second parameter of the method has a "primary" or "unique" index.
Delete Model
$flight = App\Models\Flight : : find ( one ) ; $flight - > delete ( ) ;
Delete model through primary key
App\Models\Flight : : destroy ( one ) ; App\Models\Flight : : destroy ( one , two , three ) ; App\Models\Flight : : destroy ( [ one , two , three ] ) ; App\Models\Flight : : destroy ( collect ( [ one , two , three ] ) ) ;
be careful:
destroy Method to load each model separately and call
delete Method to trigger
deleting and
deleted event.
Delete model through query
$deletedRows = App\Models\Flight : : where ( 'active' , zero ) - > delete ( ) ;
Note: Pass
Eloquent When executing a batch delete statement, it will not be triggered
deleting and
deleted Model events. Therefore, the model samples are never retrieved when the delete statement is executed.
Soft Delete
< ? php namespace App\Models ; use Illuminate\Database\Eloquent\Model ; use Illuminate\Database\Eloquent\SoftDeletes ;
class Flight extends Model
{ use SoftDeletes ;
}
skill:
SoftDeletes Will automatically
deleted_at Attribute converted to
DateTime /
Carbon example.
public function up ( )
{ Schema : : table ( 'flights' , function ( Blueprint $table ) { $table - > softDeletes ( ) ;
} ) ;
}
public function down ( )
{ Schema : : table ( 'flights' , function ( Blueprint $table ) { $table - > dropSoftDeletes ( ) ;
} ) ;
}
if ( $flight - > trashed ( ) ) {
//
}
Query Soft Delete Model
Include soft deleted models
$flights = App\Models\Flight : : withTrashed ( )
- > where ( 'account_id' , one )
- > get ( ) ;
$flight - > history ( ) - > withTrashed ( ) - > get ( ) ;
Retrieve Soft Delete Models Only
$flights = App\Models\Flight : : onlyTrashed ( )
- > where ( 'airline_id' , one )
- > get ( ) ;
Restore Soft Delete Model
$flight - > restore ( ) ;
App\Models\Flight : : withTrashed ( )
- > where ( 'airline_id' , one )
- > restore ( ) ;
$flight - > history ( ) - > restore ( ) ;
Permanently delete
//Force deletion of a single model instance $flight - > forceDelete ( ) ;
//Force deletion of all associated models $flight - > history ( ) - > forceDelete ( ) ;
Copy Model
$shipping = App\Models\Address : : create ( [
'type' => 'shipping' ,
'line_1' => '123 Example Street' ,
'city' => 'Victorville' ,
'state' => 'CA' ,
'postcode' => '90001' ,
] ) ; $billing = $shipping - > replicate ( ) - > fill ( [
'type' => 'billing'
] ) ; $billing - > save ( ) ;
Query Scope
global scope
Write Global Scope
< ? php namespace App\Scopes ; use Illuminate\Database\Eloquent\Builder ; use Illuminate\Database\Eloquent\Model ; use Illuminate\Database\Eloquent\Scope ;
class AgeScope implements Scope
{
/** *Add constraints to Eloquent query construction * * @param \Illuminate\Database\Eloquent\Builder $builder * @param \Illuminate\Database\Eloquent\Model $model * @return void */
public function apply ( Builder $builder , Model $model )
{ $builder - > where ( 'age' , '>' , two hundred ) ;
}
}
Tip: If you need to add fields in the select statement, you should use
addSelect Method instead of
select method. This will effectively prevent unintentional replacement of existing select statements.
Apply Global Scope
< ? php namespace App\Models ; use App\Scopes\AgeScope ; use Illuminate\Database\Eloquent\Model ;
class User extends Model
{
/** *The "booted" method of the model * * @return void */
protected static function booted ( )
{
static : : addGlobalScope ( new AgeScope ) ;
}
}
select * from `users` where `age` > two hundred
Anonymous Global Scope
< ? php namespace App\Models ; use Illuminate\Database\Eloquent\Builder ; use Illuminate\Database\Eloquent\Model ;
class User extends Model
{
/** *The "booted" method of the model * * @return void */
protected static function booted ( )
{
static : : addGlobalScope ( 'age' , function ( Builder $builder ) { $builder - > where ( 'age' , '>' , two hundred ) ;
} ) ;
}
}
Unscope Global
User : : withoutGlobalScope ( AgeScope : : class ) - > get ( ) ;
User : : withoutGlobalScope ( 'age' ) - > get ( ) ;
//Cancel all global scopes User : : withoutGlobalScopes ( ) - > get ( ) ;
//Cancel Partial Global Scope User : : withoutGlobalScopes ( [ FirstScope : : class , SecondScope : : class
] ) - > get ( ) ;
Local Scope
< ? php namespace App\Models ; use Illuminate\Database\Eloquent\Model ;
class User extends Model
{
/** *Query only the scope of popular users * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */
public function scopePopular ( $query )
{
return $query - > where ( 'votes' , '>' , one hundred ) ;
}
/** *Query only the active user's scope * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */
public function scopeActive ( $query )
{
return $query - > where ( 'active' , one ) ;
}
}
Use local scope
$users = App\Models\User : : popular ( ) - > active ( ) - > orderBy ( 'created_at' ) - > get ( ) ;
$users = App\Models\User : : popular ( ) - > orWhere ( function ( Builder $query ) { $query - > active ( ) ;
} ) - > get ( ) ;
$users = App\Models\User : : popular ( ) - > orWhere - > active ( ) - > get ( ) ;
dynamic scope
< ? php namespace App\Models ; use Illuminate\Database\Eloquent\Model ;
class User extends Model
{
/** *Restrict the scope of the query to include only users of the given type * * @param \Illuminate\Database\Eloquent\Builder $query * @param mixed $type * @return \Illuminate\Database\Eloquent\Builder */
public function scopeOfType ( $query , $type )
{
return $query - > where ( 'type' , $type ) ;
}
}
$users = App\Models\User : : ofType ( 'admin' ) - > get ( ) ;
Model comparison
if ( $post - > is ( $anotherPost ) ) {
//
}
if ( $post - > author ( ) - > is ( $user ) ) {
//
}
event
Note: When batch updating is performed through Eloquent
saved and
updated ,
deleting and
deleted The event will not be triggered. This is because the model is not really acquired during batch update.
< ? php namespace App\Models ; use App\Events\UserDeleted ; use App\Events\UserSaved ; use Illuminate\Foundation\Auth\User as Authenticatable ;
class User extends Authenticatable
{ use Notifiable ;
/** *Event mapping for models * * @var array */
protected $dispatchesEvents = [
'saved' => UserSaved : : class ,
'deleted' => UserDeleted : : class ,
] ;
}
Use Closures
< ? php namespace App\Models ; use Illuminate\Database\Eloquent\Model ;
class User extends Model
{
/** *The "booted" method of the model * * @return void */
protected static function booted ( )
{
static : : created ( function ( $user ) {
//
} ) ;
}
}
use function Illuminate\Events\queueable ;
static : : created ( queueable ( function ( $user ) {
//
} ) ) ;
Observer
Define Observer
php artisan make : observer UserObserver -- model = User
< ? php namespace App\Observers ; use App\Models\User ;
class UserObserver
{
/** *Handle the User 'created' event * * @param \App\Models\User $user * @return void */
public function created ( User $user )
{
//
}
/** *Handle the User 'updated' event * * @param \App\Models\User $user * @return void */
public function updated ( User $user )
{
//
}
/** *Handle the User "deleted" event * * @param \App\Models\User $user * @return void */
public function deleted ( User $user )
{
//
}
/** *Handle the User "forceDeleted" event * * @param \App\Models\User $user * @return void */
public function forceDeleted ( User $user )
{
//
}
}
use App\Models\User ; use App\Observers\UserObserver ;
/** *Register any events for your application. * * @return void */
public function boot ( )
{ User : : observe ( UserObserver : : class ) ;
}
Disable Events
use App\Models\User ; $user = User : : withoutEvents ( function ( ) use ( ) { User : : findOrFail ( one ) - > delete ( ) ;
return User : : find ( two ) ;
} ) ;
Single model saving without events
$user = User : : findOrFail ( one ) ; $user - > name = 'Victoria Faith' ; $user - > saveQuietly ( ) ;
This translation is only for learning and communication purposes. Please note the translator, source and link of the article when reprinting
Our translation work follows CC protocol If our work infringes your rights and interests, please contact us in time.
Original address: https://learnku.com/docs/laravel/8.x/elo...
Translation address: https://learnku.com/docs/laravel/8.x/elo...