Laravel eloquent tricks

65

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

if($post->wasRecentlyCreated) {
  // do something
}
$post = Post::first();
$post->title;                   // Something title

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

$user->getOriginal('title');    // Something title
// whereRaw
$orders = DB::table('posts')
    ->whereRaw('COUNT(views) > ?', [200])
    ->get();
// you can increase using
$post = Post::find($id);
$post->increment('views');

// or you can decrease using
$post = Post::find($id);
$post->decrement('views');
public function author()
{
    return $this->belongsTo(Author::class)->withDefault([
        'name' => 'Someone'
    ]);
}
$post = Post::find($id);
$post->views++;
$post->save();
public function author()
{
    return $this->belongsTo(Author::class)->withDefault();
}

Comments

Submit
0 Comments