When I use Query Builder I Always find myself doing something like this:
$item = \DB::table('table')->where('slug',$slug)->first();
if ($item===null)
throw \Exception('Not found');
This could be easly solved if there were a firstOrFail() like Eloquent:
$item = \DB::table('table')->where('slug',$slug)->firstOrFail();
Is Eloquent the only way to use firstOrFail()
? Does Query Builder allow something like this?
You can add it yourself to the query builder, via a macro:
DB::query()->macro('firstOrFail', function () {
if ($record = $this->first()) {
return $record;
}
throw new Exception('No records found');
});
Then you can use it the same way you do Eloquent:
$item = DB::table('table')->where('slug', $slug)->firstOrFail();
you are almost there, laravel does provide a way to check something like this
DB::table('table')->where('slug', $slug)->exists()
DB::table('table')->where('slug', $slug)->doesntExist()
it will return boolean, hope this helps
Update: how i did it in projects was
function checkIfExists($table, $value, $field = 'id'){
return DB::table($table)->where($field, $value)->exists()
}
function getFirst($table, $value, $field = 'id'){
return DB::table($table)->where($field, $value)->first()
}
and then use this function like this
if(checkIfExists('users', 2))
$user = getFirst('users', 2)
else
// throw exception or something
Hope this helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.