Summary of 10 Useful Uses in Laravel

  • 2021-12-09 08:38:22
  • OfStack

Preface

This article introduces some common uses in Laravel. Well, maybe you will use them. . .

1. Specify properties in the find method


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

2. Clone 1 Model

One Model can be cloned by replicate method


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

3. Determine whether two Model are the same

Check whether the ID of two Model is the same using is method


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

4. Reload 1 Model


$user = User::find(1);
$user->name; // 'Peter'
//  If  name  Updated, such as by  peter  Update to  John
$user->refresh();
$user->name; // John

5. Load the new Model


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

6. Update Model with association

When updating an association, all Model can be updated using the push method


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 only  User Model
$user->push(); //  Update  User  And  Phone Model

7. Customize Soft Delete Fields

Laravel uses deleted_at as the soft delete field by default, and we change deleted_at to is_deleted in the following way


class User extends Model
{
 use SoftDeletes;
  * deleted_at  Field .
  *
  * @var string
  */
 const DELETED_AT = 'is_deleted';
}

Or use an accessor


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

8. Query Model changed properties


$user = User::first();
$user->name; // John
$user->name = 'Peter';
$user->save();

dd($user->getChanges());
//  Output: 
[
 'name' => 'John',
 'updated_at' => '...'
]

9. Query whether 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

Differences between getChanges () and getDirty ()

The getChanges () method is used to output the result set after the save () method

The getDirty () method is used to output the result set before the save () method

10. Query Model information before modification


$user = User::find(1);
$newUser = $user->replicate();
$newUser->save();
0

Summarize


Related articles: