Home >PHP Framework >Laravel >Do you know how to use Laravel in these 10 ways?
The following column will introduce you to 10 usages in Laravel from the Laravel Tutorial column. I hope it will be helpful to friends in need!
1. Specify attributes in the find method
User::find(1, ['name', 'email']); User::findOrFail(1, ['name', 'email']);
2. Clone a Model
Use the replicate method to clone a Model Model
$user = User::find(1); $newUser = $user->replicate(); $newUser->save();
3. Determine whether the two Models are the same
Check whether the IDs of the two Models are the same using the is method
$user = User::find(1); $sameUser = User::find(1); $diffUser = User::find(2); $user->is($sameUser); // true $user->is($diffUser); // false;
4 . Reload a Model
$user = User::find(1); $user->name; // 'Peter' // 如果 name 更新过,比如由 peter 更新为 John $user->refresh(); $user->name; // John
5. Load a new Model
$user = App\User::first();$user->name; // John // $updatedUser = $user->fresh(); $updatedUser->name; // Peter $user->name; // John
6. Update the associated Model
When updating the association, use the push method to update all Model
class User extends Model{ public function phone() { return $this->hasOne('App\Phone'); }}$user = User::first(); $user->name = "Peter"; $user->phone->number = '1234567890'; $user->save(); // 只更新 User Model $user->push(); // 更新 User 和 Phone Model
7. Customize the soft deleted field
Laravel uses deleted_at as the soft deleted field by default , we change deleted_at to is_deleted
class User extends Model{ use SoftDeletes; * deleted_at 字段. * * @var string */ const DELETED_AT = 'is_deleted';}
in the following ways or use the accessor
class User extends Model{ use SoftDeletes; public function getDeletedAtColumn(){ return 'is_deleted'; }}
8. Query the changed attributes of the Model
$user = User::first(); $user->name; // John $user->name = 'Peter'; $user->save(); dd($user->getChanges());// 输出: [ 'name' => 'John', 'updated_at' => '...' ]
9. Query 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
The difference between getChanges() and getDirty()
getChanges() method is used to output the result set after the save() method
getDirty() method is used before the save() method to output the result set
10. Query the Model information before modification
$user = App\User::first(); $user->name; //John $user->name = "Peter"; //Peter $user->getOriginal('name'); //John $user->getOriginal(); //Original $user record
The above is the detailed content of Do you know how to use Laravel in these 10 ways?. For more information, please follow other related articles on the PHP Chinese website!