10 Laravel 7 Eloquent Tricks

Laravel Eloquent ORM provides a whole lot of useful functionality that allows you to work with your database tables and relationships using an eloquent expressive syntax.

So, In here are some of the features which you might often reach out for ease of use and cleaner code in your laravel project.

1. Finding first record or records

Here’s an example of finding a post with id.

// Instead of this
$post = Post::find($id);

if(!$post) {
   abort(404);
}

// Do this
$post = Post::findOrFail($id);

Or, you can even find multiple records at once by passing array of ids as second argument.

$posts = Post::find([1,2,3]);

Even specify id with the fields to select as the second argument.

$post = Post::find(1, ['title', 'description']);
$post = Post::findOrFail(1, ['title', 'description']);

2. Model booted() method

In this method, you can specify what to do on different model events such as creating, updating, deleting etc by passing a closure function.

class User extends Model
{
    public static function booted()
    {
        static::creating(function ($user) {
            // delete comments
            // delete images
        });

        static::updating(function ($post) {
            // update comments
            // update images
        });
    }
}

3. Change default model properties

These are only few of the default properties of an eloquent model you often would reach out. You can change the values according to your needs.

class Post extends Model
{
    // The table associated with the model.
    protected $table = 'posts';

    // fields that can be filled using mass assignment Post::create()
    protected $fillables = ['title' , 'description'];

    // Eager load relations everytime you fetch posts
    protected $with = ['comments'];

    // appends accessors to the model's array form.
    protected $appends = ['formatted_date', 'short_title'];

    // The primary key associated with the table.
    protected $primaryKey = 'post_id';

    // Indicates if the IDs are auto-incrementing.
    public $incrementing = false;

    // Indicates if the model should be timestamped.
    public $timestamps = false;

    // The storage format of the model's date columns.
    protected $dateFormat = 'U';

    // change the names of the columns used to store the timestamps
    const CREATED_AT = 'creation_date';
    const UPDATED_AT = 'last_update';
}

you can retrieve the number of results from a relationship without actually loading them you may use the withCount method.


Define a relation comments():

public function comments() 
{
    return $this->hasMany(Comment::class);
}

Then, you can use like this:

$posts = Post::withCount('comments')->get();

foreach ($posts as $post) {
    echo $post->comments_count;
}

5. Return a default model instead of null in relation

Instead of checking relation data everywhere

{{ $post->author->name ?? '' }}

You can return a default empty model with no relation attached to it.

public function author()
{
    return $this->belongsTo(Author::class)->withDefault();
}

You can even set a default values for default empty model.

public function author()
{
    return $this->belongsTo(Author::class)->withDefault([
        'name' => 'Someone'
    ]);
}

6. Get original attributes

You can retrieve original values like this after mutating values in your model.

$post = Post::first();
$post->title;                   // Something title

$post->title = "new title";    // new title

$user->getOriginal('title');    // Something title

This specially comes in handy when you have accessor same as the name of your column field. For example..

class Post extends Model
{
    public function getImageAttribute($value)
    {
        return asset("storage/$value");
    }
//....

$post->image; // will return https://url.com/image-location.jpg

$post->getOriginal('image'); // image-location.jpg

7. Use raw query

Sometimes, you just need some raw sql query in your Eloquent builder. Luckily, you can do this with this function.

// whereRaw
$orders = DB::table('posts')
    ->whereRaw('COUNT(views) > ?', [200])
    ->get();

8. Create model with additional files

This artisan command will only create a model.

php artisan make:model Post

There are helpful flags which can generate files related to the model for you.

php artisan make:model Post -fmcr

  • -f will create a factory file
  • -m will create a migration file
  • -c will create a controller file
  • -r will create a controller with resourceful functions

9. Check if model was recently created or changed.

You can determine if the model is recently created using wasRecentlyCreated.

$post = Post::create($attributes);

if($post->wasRecentlyCreated) {
  // do something
}

Or check if the model attributes has changed or modified using isDirty().

$post = Post::first();
$post->isDirty();          //false

$post->title = "New Title";
$post->isDirty();          //true

10. Increment or decrement a field

Instead of doing this way:


$post = Post::find($id);
$post->views++;
$post->save();

You can do this way:

// you can increase using
$post = Post::find($id);
$post->increment('views');

// or you can decrease using
$post = Post::find($id);
$post->decrement('views');

If you find this useful, checkout other of our tutorials and projects. There might find something to learn and new thing you didn’t know about.

Total
2
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts
Total
2
Share