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.
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 ]);
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
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' ];
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()');