Laravel Advanced Eloquent Tips and Tricks

Today, We want to share with you Laravel Advanced Eloquent Tips and Tricks with Example.In this post we will show you laravel update related model, hear for Laravel Eloquent Amazing Tips and Tricks we will give you demo and example for implement.In this post, we will learn about laravel update related model with an example.

Laravel Advanced Eloquent Tips and Tricks with Example

There are the Following The simple About Laravel Advanced Eloquent Tips and Tricks with Example Full Information With Example and source code.

As I will cover this Post with live Working example to develop laravel eloquent insert or update, so the Tips, Tricks, and Good Practices with Laravel’s Eloquent for this example is following below.

1. Increments and Decrements

Laravel 5.8 Increments and Decrements

$product = Product::find($product_id);
$product->cat_count++;
$product->save();
$product = Product::find($product_id);
$product->increment('cat_count');
Product::find($product_id)->increment('cat_count');
Product::find($product_id)->increment('cat_count', 10); // +10
Product::find($produce_id)->decrement('stock'); // -1

2. XorY methods

Simple Laravel : findOrFail():

$member = Member::find($id);
if (!$member) { abort (404); }
$member = Member::findOrFail($id);

Example 2 – firstOrCreate():

$member = Member::where('email', $email)->first();
if (!$member) {
  Member::create([
    'email' => $email
  ]);
}
$member = Member::firstOrCreate(['email' => $email]);

3. Model boot() method

magical place called boot() in an Eloquent model

class Member extends Model
{
    public static function boot()
    {
        parent::boot();
        static::updating(function($model)
        {
           // MAin Logics
        });
    }
}
public static function boot()
{
  parent::boot();
  self::creating(function ($model) {
    $model->uuid = (string)Uuid::generate();
  });
}

4. Relationship

Relationship with conditions and ordering

public function members() {
    return $this->hasMany('App\Member');    
}
public function approvedMembers() {
    return $this->hasMany('App\Member')->where('approved', 1)->orderBy('email');
}

5. Model properties

timestamps, appends etc.

class Member extends Model {
    protected $table = 'members';
    protected $fillable = ['email', 'password']; 
    protected $dates = ['created_at', 'deleted_at'];
    protected $appends = ['field1', 'field2'];
}
protected $primaryKey = 'uuid'; 
public $incrementing = false;
protected $perPage = 25;
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at'; 
public $timestamps = false;

6. Find multiple entries

find() method

$member = Member::find(1);

//multiple
$members = Member::find([1,2,3]);

7. WhereX

$members = Member::where('approved', 1)->get();

// do this-

$members = Member::whereApproved(1)->get(); 

pre-defined methods in Eloquent

Member::whereDate('created_at', date('Y-m-d'));
Member::whereDay('created_at', date('d'));
Member::whereMonth('created_at', date('m'));
Member::whereYear('created_at', date('Y'));

8. Order by Mutator

function getFullNameAttribute()
{
  return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
}
$clients = Client::orderBy('full_name')->get(); // doesn't work
$clients = Client::get()->sortBy('full_name'); // works! fine

9. global scope

Laravel Default ordering in global scope

protected static function boot()
{
    parent::boot();

    // Order by name ASC
    static::addGlobalScope('order', function (Builder $builder) {
        $builder->orderBy('name', 'asc');
    });
}

10. Raw query in Laravel

Raw query methods

// whereRaw
$orders = DB::table('orders')
    ->whereRaw('price > IF(state = "TX", ?, 100)', [200])
    ->get();

// havingRaw
Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();

// orderByRaw
Member::where('created_at', '>', '2016-01-01')
  ->orderByRaw('(updated_at - created_at) desc')
  ->get();
Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Laravel Advanced Eloquent Tips and Tricks with Example.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment