Laravel Eloquent non-lambda parameters - php

I'm trying to retrieve a number of results from database using eloquent.
I dont have problem with that.
Example code
$flights = App\Flight::where('active', 1)
->orderBy('name', 'desc')
->take(10)
->get();
Now lets suppose I have a variable that if it's true i want to add one more WHERE clause. For example if $domestic == true then i want something like this:
$flights = App\Flight::where('active', 1)
->where('domestic',1)
->orderBy('name', 'desc')
->take(10)
->get();
So I dont like to do, because it's not nice.
if($domestic) {
$flights = App\Flight::where('active', 1)
->where('domestic',1)
->orderBy('name', 'desc')
->take(10)
->get();
} else {
$flights = App\Flight::where('active', 1)
->orderBy('name', 'desc')
->take(10)
->get();
}
Ideally i want to pass only the where clause eg.
if(#domestic) { $flights->where('domestic',1) }
But this is not working.
What is the best way to pass additional where clauses whenever needed?

$flights = App\Flight::where('active', 1)
->orderBy('name', 'desc')
->when($domestic, function ($query){
return $query->where('domestic',1)
})
->take(10)
->get();
The laravel query builder has some real gems like the when clause, the when clause will only execute the closure if the first parameter is true (in this case $domestic)
This specific function can be found here. On the same way more of these functions can be found.

Solution is:
$flights = App\Flight::where('active', 1);
if($domestic) {
$flights->where('domestic',1);
}
$results = $flights->orderBy('name', 'desc')
->take(10)
->get();

Use Query Scopes
Write them on your model, quick example on flight model:
public function scopeIsDomestic($query,$domestic){
if($domestic == 1){
return $query->where('domestic',1);
}else{
return $query; //you can return the inverse if you need it -> where domestic <> 1
}
}
And now use it like this
$flights = App\Flight::where('active', 1)
->isDomestic(1)
->orderBy('name', 'desc')
->take(10)
->get();
It provides a nice way to keep the code maintainable since you can update the scope on all your queries at the same time by modifying it on a single place

Related

OrderBy its not wokring on laravel

i have a problem when doing "orderBy" name product. here are my codes
$resume = Transaction::with(['product' => function ($q) {
$q->orderBy('name_product','ASC');
}])
->where('status', 'keluar')
->where('status', 'masuk')
->get();
but my code its not working... here is the output
result
Use the collection to sort instead. It allows for sorting based on a nested property.
$resume = Transaction::with('product')
->where('status', 'keluar')
->where('status', 'masuk')
->get()
->sortBy('product.name_product')
->values();
Because you are applying condition to product, not in transaction.
I have another suggestion use whereHas.
Transaction::whereHas('product', function($query) {
$query->->orderBy('name_product','ASC');
})->where('status', 'keluar')
->where('status', 'masuk')
->get();

Laravel Collection Query, Where I am going wrong?

My tables looks like this
area_trip
|id|dispatch_id|trip_id|status|
equipment_trip
|equipment_id|trips_id|dispatch_id|
trips
|id|dispatch_id|status
I am trying to pass collection to my resource. Can someone check my query and tell me what I am doing wrong as following query returning all the data matches dispatch_id whether it matches equipment_id or not. Btw I am new to laravel.
return
Resources::collection(
area_trip::where('dispatch_id', $request->dispatch_id)
->where('status', 1)
->orWhere('status', 9)
->whereHas('equipment_trip', function($query) use ($request) {
$query->where('equipment_trip.equipment_id', '=', $request->equipment_id);
})
->with(['equipment_trip', 'createdBy', 'updatedBy', 'area', 'trips'])
->orderBy('tripStartDate', 'ASC')
->orderBy('status', 'ASC')
->get());
Here is the relationship set up in area_trip model
public function equipment_trip()
{
return $this->belongsTo(equipment_trip::class, 'trip_id', 'trips_id');
}
I believe your whereHas sub query is incorrect also instead of where and orWhere use where in and you can define all statuses necessary, try this:
Resource::collection(area_trip::where('dispatch_id', $request>dispatch_id)
->whereIn('status', [1, 9])
->whereHas('equipment_trip', function($query) use ($request) {
return $query->where('equipment_id', '=', $request->equipment_id);
})
->with(['equipment_trip', 'createdBy', 'updatedBy', 'area', 'trips'])
->orderBy('tripStartDate', 'ASC')
->orderBy('status', 'ASC')
->get());

How do you filter the user with hasRole() in Laravel 5 within relational query?

I want to filter my query and return only if the user hasRole "Premium" and limit the result to 10.
Along with this query is a count of records which Conversion has and sort it in DESC order by total column.
Right now I have a working query that returns the count of Conversion and with a User but without user filter Role.
// Model Conversion belongs to User
// $from & $end uses Carbon::createDate()
// Current code
$query = Conversion::select('user_id',DB::raw('COUNT(*) as total'))
->whereBetween('created_at', [$from,$end])
->where('type','code')
->where('action','generate')
->whereNotNull('parent_id')
->with('user')
->groupBy('user_id')
->orderBy('total', 'DESC')
->take(10)
->get();
// current result
foreach ($query as $q) {
$q->user->name; // To access user's name
$q->total; // To access total count
}
// I tried this but no luck
$query = Conversion::select('user_id',DB::raw('COUNT(*) as total'))
->whereBetween('created_at', [$from,$end])
->where('type','code')
->where('action','generate')
->whereNotNull('parent_id')
->with('user', function($q) {
$q->hasRole('Premium');
})
->groupBy('user_id')
->orderBy('total', 'DESC')
->take(10)
->get();
You need to use whereHas instead of with, like this:
->whereHas('user', function ($query) {
$query->where('role','Premium');
})
Use the whereHas() instead of with(). Also, you can't use hasRole() if it's not a local scope:
->whereHas('user.roles', function($q) {
$q->where('name', 'Premium');
})

cant get the data I want from two different tables using Laravel

I have a table called instructor_class: user_id, class_id and I have another table classes: id, time, active.
I would like to show classes for a single user but only those classes that active is 0 or 1.
My current code looks like this:
return InstructorClass::with('classes.session')->where('user_id', '=', $userId)->get();
This code is displaying me everything, then I tried the following code:
$active = 1;
return InstructorClass::with(['classes' => function ($q) use ($active) {
$q->where('active', '=', $active); // '=' is optional
}])
->where('user_id', '=', $userId)
->get();
This again returns me same records, but of course the class property is null for each record, which at some point looks correct, but my point is if the 'active' field does not corresponds at the classes table do not show the record, seems like the where() stm within with() is optional..
I am kinda stuck here...
Would appreciate your help, opinions!
You can use ::has('classes') to only return the models that have related classes
return InstructorClass::has('classes')->with(['classes' => function ($q) use ($active) {
$q->where('active', $active);
}])
->where('user_id', '=', $userId)
->get();
Never thought it could be this simple:
return InstructorClass::with('classes.session')
->join('classes', 'classes.id', '=', 'instructor_class.class_id')
->where('classes.active', '=', 1)
->where('user_id', '=', $userId)
->get();

Need help getting the right query on repository laravel 4.2

I need to fetch the categorie name from the images to the ImagesRepository
So far in ImagesRepository i got:
public function latest($limit = 8)
{
return $this->image->whereNotNull('poster')
->orderBy('id', 'desc')
->limit($limit)
->get();
}
I tried using leftJoin but it didnt work:
public function latest($limit = 8)
{
return $this->image->whereNotNull('poster')
->orderBy('id', 'desc')
->limit($limit)
->leftJoin('category', 'id', '=', 'category_id')
->get();
}
Now i need to get the id from the Category Table that matches the category_id so i can get the right url link to the post.
Cause my result right now is :
localhost/test/1/name-1
and i need to get:
localhost/test/1-flowers/name-1
OK so after carefully looking at laravel documentation i figured it out the solution since they are already relationships in the eloquent all i have to do is call the table by simple adding a line...
public function latest($limit = 8)
{
return $this->image->whereNotNull('poster')
->with('category')
->orderBy('id', 'desc')
->limit($limit)
->get();
}

Categories