Skip to content

Instantly share code, notes, and snippets.

@bhuvidya
Last active May 2, 2016 03:26
Show Gist options
  • Save bhuvidya/26f9c9b709ee60ee328217dcfd21c296 to your computer and use it in GitHub Desktop.
Save bhuvidya/26f9c9b709ee60ee328217dcfd21c296 to your computer and use it in GitHub Desktop.

Cool Eloquent Query/Model Stuff

I use Eloquent ORM in Laravel apps. I am torn between raw SQL (where you have a lot of power) and using an ORM, but a lot of times you can kinda walk a tightrope between the two. This gist is a way of collecting cool, more unusual Eloquent query techniques and tips and tricks.

updateOrCreate()

insert a new row or update an existing one in one statement. updateOrCreate takes two params, an array of attributes to search table on, and then an array of values to set if an existing record is found

Model::updateOrCreate([ 'user_id' => $user->user_id ], [ 'name' => 'bob' ]);

you don;t have to specify the $values 2nd parameter, which is essentially saying all the necessary data is in the key attributes array

Model::updateOrCreate([ 'user_id' => $user->user_id, 'topic_id' => $topic_id ]);

eloquent relationships are cached

so you can do

if ($qst->topic) {
    $t = $qst->topic;
}

where

class Qst implements Model
...
    public fucntion topic()
    {
        return $this->hasOne('App\Models\Topic', 'topic_id', 'topic_id');
    }
...

and the relationship is only loaded once

dates mutator

the $dates mutator on Model classes only needs to specify additional model attributes, you don't need to specify the standard ones such as updated_at. the following two declarations are equivalent:

protected $dates = [ 'created_at', 'updated_at', 'last_status_update', 'ans_when' ];
protected $dates = [ 'last_status_update', 'ans_when' ]; 

using DB::raw() in less familiar places

i used to think DB::raw() was only used in a query chain, like User::whereRaw('user_id < 1000') etc etc. but here are some other places you can use it

this example shows how to access builtin MySql functions when creating new models:

$qst = new Qst;
$qst->uuid = DB::raw('uuid()');
$qst->last_status_update = DB::raw('now()');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment