Laravel Eloquent Tips and Tricks

Laravel Eloquent Tips and Tricks

Here is the list of some of the useful Laravel Eloquent Tips and Tricks which are usually ignored by developers and not used as much as these should be.

1.) Expressive where syntax

$products = Product::where('category' , 3);

you can do this instead

$product = Product::whereCategory(3);

just append column name in plural case after where

2.) Date filtering

$q->whereDate('created_at', date('Y-m-d'));
$q->whereDay('created_at', date('d'));
$q->whereMonth('created_at', date('m'));
$q->whereYear('created_at', date('Y'));

3.) Disable timestamps updation while saving

You may need to disable timestamp updation on particular operations, you can do this as below. Obviously if you need to do this permanently you can do the same by defining $timestamp property to false in your model.

$product = Product::find($product_id);
$product->price = $price;
$product->save(['timestamps' => false]);

4.) Retrieving random rows

Questions::orderByRaw('rand()')->take(10)->get();

Read http://codeway.co.in/2015/08/mysql-pagination-with-random-ordering/ for more details on how this works.

5.) Conditional and ordered relationships

you can easily add conditions and ordering to your relationship destinations. You can be creative and use this technique to create multiple relations with different conditions to the same model.

//in your model
 public function categories(){
 $this->hasMany('category')->where('user_id', Auth::user()->id)->orderBy('product_count');
 }

6.) Easy Incrementing & Decrementing

Eloquent provides us with two easy to use methods for incrementing and decrementing values.

Normally you will do it like this.

$post = Post::find($post_id);
$post->likes_count = $post->likes_count + 1;
$post->save();

Easier way

$post = Post::find($post_id);
$post->increment('likes_count');

You don’t need to call save as well, changes are persisted to database when you use this method. Both increment and decrements also accept a second parameter which defines by what value to increment or decrement.

$post->increment('likes_count', 10); // increment 'likes_count' column value by 10

decrement work same as increment

$post->decrement('likes_count', 10); // decrement by 1 if you ignore second parameter

Make sure you database columns is of number(integer) type and doesn’t allows null. I have seen these functions not working with null values. So make sure column value is 0 by default and not null

7.) Lists with Mutations

Accessors and mutators allow you to format Eloquent attributes when retrieving them from a model or setting their value. To define a mutator, define a setFooAttribute method on your model where Foo is the “camel” cased name of the property you wish to access.

// user model
function getFullNameAttribute(){
   return $this->first_name . ' ' . $this->last_name;
}

User::lists('full_name', 'id');

 

8.) Filters records which has child rows

Getting all categories which has products. Has function can be used to eliminate records which don’t have child records.

$categories = Category::with('products')->has('products')->get();

9.) Return relations on saving model

$post = new Post();
$post->fill(Input::all());
$post->user_id = Auth::user()->id;
$post->user;
$post->save();

 

The following two tabs change content below.

Ankit Kumar

Team Leader at Logiciel Solutions
This is my personal blog. I post about Laravel, Angular, SQL and Web Technologies here. I have been into web development for 7 years and learning new things always interest me. Looking forward to find a teacher in you all.
  • Vikash Pathak

    A list of useful tricks.

    • Ankit Kumar

      Thank you 🙂