Eloquent Tips and Tricks - Laravel

morcosgad

Morcos Gad

Posted on April 5, 2022

Eloquent Tips and Tricks - Laravel

I found this wonderful article https://laravel-news.com/eloquent-tips-tricks that contains a lot of tips, specifically 20 tips that will help you in your advice with dealing with databases and will make your next project more powerful and accurate, and I will talk about some points that interest me

  • Increments and Decrements
// Instead of this
$article = Article::find($article_id);
$article->read_count++;
$article->save();

// You can do this
$article = Article::find($article_id);
$article->increment('read_count');

Article::find($article_id)->increment('read_count');
Article::find($article_id)->increment('read_count', 10); // +10
Product::find($produce_id)->decrement('stock'); // -1
Enter fullscreen mode Exit fullscreen mode
  • Model boot() method
public static function boot()
{
  parent::boot();
  self::creating(function ($model) {
    $model->uuid = (string)Uuid::generate();
  });
}
Enter fullscreen mode Exit fullscreen mode
  • Model properties: timestamps, appends etc
class User extends Model {
    protected $table = 'users';
    protected $fillable = ['email', 'password']; // which fields can be filled with User::create()
    protected $dates = ['created_at', 'deleted_at']; // which fields will be Carbon-ized
    protected $appends = ['field1', 'field2']; // additional values returned in JSON
}

protected $primaryKey = 'uuid'; // it doesn't have to be "id"
public $incrementing = false; // and it doesn't even have to be auto-incrementing!
protected $perPage = 25; // Yes, you can override pagination count PER MODEL (default 15)
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at'; // Yes, even those names can be overridden
public $timestamps = false; // or even not used at all
Enter fullscreen mode Exit fullscreen mode
  • WhereX
$users = User::where('approved', 1)->get();
$users = User::whereApproved(1)->get();

User::whereDate('created_at', date('Y-m-d'));
User::whereDay('created_at', date('d'));
User::whereMonth('created_at', date('m'));
User::whereYear('created_at', date('Y'));
Enter fullscreen mode Exit fullscreen mode
  • BelongsTo Default Models
{{ $post->author->name ?? '' }}

// we can assign default property values to that default model
public function author()
{
    return $this->belongsTo('App\Author')->withDefault([
        'name' => 'Guest Author'
    ]);
}
Enter fullscreen mode Exit fullscreen mode
  • Order by Mutator
// Imagine you have this
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!
Enter fullscreen mode Exit fullscreen mode
  • 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');
    });
}
Enter fullscreen mode Exit fullscreen mode
  • 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
User::where('created_at', '>', '2016-01-01')
  ->orderByRaw('(updated_at - created_at) desc')
  ->get();
Enter fullscreen mode Exit fullscreen mode
  • Chunk() method for big tables
// Instead of

$users = User::all();
foreach ($users as $user) { }

// You can do

User::chunk(100, function ($users) {
    foreach ($users as $user) {
        // ...
    }
});
Enter fullscreen mode Exit fullscreen mode
  • Override updated_at when saving
$product = Product::find($id);
$product->updated_at = '2019-01-01 10:00:00';
$product->save(['timestamps' => false]);
Enter fullscreen mode Exit fullscreen mode
  • What is the result of an update()
$result = $products->whereNull('category_id')->update(['category_id' => 2]);
Enter fullscreen mode Exit fullscreen mode
  • orWhere with multiple parameters
// you can pass an array of parameters to orWhere() “Usual” way

$q->where('a', 1);
$q->orWhere('b', 2);
$q->orWhere('c', 3);

$q->where('a', 1);
$q->orWhere(['b' => 2, 'c' => 3]);
Enter fullscreen mode Exit fullscreen mode

I tried to present some basic points, but to go deeper, visit the source.
I hope you enjoyed with me and I adore you who search for everything new.

💖 💪 🙅 🚩
morcosgad
Morcos Gad

Posted on April 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related