xxxxxxxxxx
Visitor::select('country')
->withCount('id')
->groupBy('country')
->latest()
->get()
//or
Visitor::query()->groupBy('country')->orderByDesc('count')->select('country' ,DB::raw('COUNT(1) as count'))->get()
xxxxxxxxxx
$results = DB::table('orders')
->where('branch_id', Auth::user()->branch_id)
->when($request->customer_id, function($query) use ($request){
return $query->where('customer_id', $request->customer_id);
})
->get();
xxxxxxxxxx
$query = Author::query();
$query->when(request('filter_by') == 'likes', function ($q) {
return $q->where('likes', '>', request('likes_amount', 0));
});
$query->when(request('filter_by') == 'date', function ($q) {
return $q->orderBy('created_at', request('ordering_rule', 'desc'));
});
$authors = $query->get();
xxxxxxxxxx
Model::where(function ($query) {
$query->where('a', '=', 1)
->orWhere('b', '=', 1);
})->where(function ($query) {
$query->where('c', '=', 1)
->orWhere('d', '=', 1);
});
xxxxxxxxxx
This:
Model::where()->get();
Is the same as:
Model::query()->where()->get();
Model::query() used to instantiate a query and then build up conditions based on request variables.
$query = Model::query();
if ($request->color) {
$query->where('color', $request->color);
}
xxxxxxxxxx
//No translations
$banners = Banner::where(function ($query) {
$query->where('title', 'like', '%'.$this->search.'%')
->orWhere('description', 'like', '%'.$this->search.'%');
})
->where('type_id', $this->type->id)
->orderBy($this->sort, $this->direction)
->paginate($this->cant);
//with translations
$banners = Banner::whereNull('deleted_at')->withTranslation()
->where(function ($query) {
$query->where('type_id', $this->type->id)
->orWhereTranslationLike('title', '%'.$this->search.'%')
->where('type_id', $this->type->id)
->orWhereTranslationLike('description', '%'.$this->search.'%')
->where('type_id', $this->type->id);
})
->orderBy($this->sort, $this->direction)
->paginate($this->cant);
xxxxxxxxxx
// Retrieve a model by its primary key...
$flight = App\Models\Flight::find(1);
// Retrieve the first model matching the query constraints...
$flight = App\Models\Flight::where('active', 1)->first();
// Shorthand for retrieving the first model matching the query constraints...
$flight = App\Models\Flight::firstWhere('active', 1);
xxxxxxxxxx
DB::table('users')->insert([
'email' => 'kayla@example.com',
'votes' => 5
]);
xxxxxxxxxx
return Destination::orderByDesc(
Flight::select('arrived_at')
->whereColumn('destination_id', 'destinations.id')
->orderBy('arrived_at', 'desc')
->limit(1)
)->get();
xxxxxxxxxx
php artisan make:model Flight --migration
php artisan make:model Flight -m
xxxxxxxxxx
$users = DB::table('users')
->when($role, function ($query, $role) {
$query->where('role_id', $role);
})
->get();