10 Eloquent Features That You Might Not Know About

Daan
Daan
May 31 · 3 min read

1. Custom timestamp column names

class User extends Model
{
const CREATED_AT = 'created';
const UPDATED_AT = 'last_update';
const DELETED_AT = 'removed';
}

2. The exists property

$user = new User;
$user->name = 'George';
$user->email = 'george@example.com';
$user->password = 'secret';
$user->exists; // false$user->save();$user->exists; // true

3. Dirty

$user = User::first();$user->isDirty(); // false$user->name = 'James';$user->isDirty(); // true
$user->isDirty('email'); // false
$user->isDirty('name'); // true
$user->getDirty(); // ["name" => "James"]

4. Original

$user = User::first();
$user->name = 'James';

$user->getOriginal(); // Array with "name" => "George"
$user->getOriginal('name'); // "George"

5. Cloning a model

$user = User::first();
$clonedUser = $user->replicate();

6. Convert a model or collection to array

// Convert a model instance to an array
$user = User::first();
$user->toArray();
// Convert a collection to an array
$users = User::all();
$users->toArray();

7. Refresh

$user= User::where('name', 'George')->first();
$user->name= 'James';
$user->address->city = "New York";
$user->refresh();$user->name; // "George"
$user->address->city; // "Washington"

8. Without events

$user = User::withoutEvents(function () {
return factory(User::class)->create();
});

9. Push

$user = User::where('name', 'George')->first();
$user->age = 42;
$user->address->city = "New York";
$user->save();
$user->push();

10. Force a delete on a soft delete model

$user = User::first();$user->forceDelete();

The Startup

Medium's largest active publication, followed by +479K people. Follow to join our community.

Daan

Written by

Daan

Backend developer from The Netherlands. Crypto enthusiast.

The Startup

Medium's largest active publication, followed by +479K people. Follow to join our community.