jcadima
7/31/2018 - 7:39 PM

Laravel Eloquent Tips


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


// Do:
$article = Article::find($article_id);
$article->increment('read_count');

// Also:
Article::find($article_id)->increment('read_count');
Article::find($article_id)->increment('read_count', 10); // +10
Product::find($produce_id)->decrement('stock'); // -1

// ============ XorY methods  =============
// Instead of :
$user = User::find($id);
if (!$user) { abort (404); }

// Do: 
$user = User::findOrFail($id);

// Instead of:
$user = User::where('email', $email)->first();
if (!$user) {
  User::create([
    'email' => $email
  ]);
}

// Do:
$user = User::firstOrCreate(['email' => $email]);

// ======= Model Relationships ========

// Regular Relationships:
public function users() {
    return $this->hasMany('App\User');    
}

// You can also do this:
public function approvedUsers() {
    return $this->hasMany('App\User')->where('approved', 1)->orderBy('email');
}

// ====== Find, Where ========

// We can find a resource with:
$user = User::find(1);

// But we can also find multiple users:
$users = User::find([1,2,3]);

// Turn :
$users = User::where('approved', 1)->get();

// Into:
$users = User::whereApproved(1)->get(); 

// Predefined Eloquent date/times:
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'));


//  ======= 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();

// ======== Replicate rows =======
// make a copy of database entry
$task = Tasks::find(1);
$newTask = $task->replicate();
$newTask->save();