This article introduces some common Laravel usages, well, you might be able to use them…

1. Specify attributes in the find method

User::find(1, ['name', 'email']);
User::findOrFail(1, ['name', 'email']);
Copy the code

You can Clone a Model with the replicate method

$user = User::find(1);
$newUser = $user->replicate();
$newUser->save();
Copy the code

3. Check whether the two models are the same. Check whether the IDS of the two models are the same

$user = User::find(1);
$sameUser = User::find(1);
$diffUser = User::find(2);
$user->is($sameUser); // true
$user->is($diffUser); // false;
Copy the code

4. Reload a Model

$user = User::find(1); $user->name; // 'Peter' // If name is updated, such as by Peter to John $user->refresh(); $user->name; // JohnCopy the code

5. Load the new Model

$user = App\User::first();
$user->name;    // John
//
$updatedUser = $user->fresh(); 
$updatedUser->name;  // Peter
$user->name;    // John
Copy the code

Update all models with associations using the push method when updating associations

class User extends Model { public function phone() { return $this->hasOne('App\Phone'); } } $user = User::first(); $user->name = "Peter"; $user->phone->number = '1234567890'; $user->save(); // update User Model $User ->push(); // Update User and Phone modelsCopy the code

Laravel uses deleted_AT as the default soft delete field. We changed deleted_AT to IS_deleted in the following way

class User extends Model { use SoftDeletes; * * @var string */ const deleted_at = 'is_deleted'; }Copy the code

Or use accessors

class User extends Model { use SoftDeletes; public function getDeletedAtColumn(){ return 'is_deleted'; }}Copy the code

8. Query the properties changed by Model

$user = User::first(); $user->name; // John $user->name = 'Peter'; $user->save(); dd($user->getChanges()); / / output: [' name '= >' John ', 'updated_at' = > '... ']Copy the code

9. Check whether the Model has changed

$user = User::first();
$user->name;    // John
$user->isDirty();  // false 
$user->name = 'Peter'; 
$user->isDirty();  // true
$user->getDirty();  // ['name' => 'Peter']
$user->save();   
$user->isDirty();  // false
Copy the code

The difference between getChanges() and getDirty() is used to print the result set after the save() method

10. Query the Model information before the modification

$user = App\User::first();
$user->name;     //John
$user->name = "Peter";   //Peter
$user->getOriginal('name'); //John
$user->getOriginal();   //Original $user record
Copy the code