Skip to content
Advertisement

Adding custom collection to the eloquent within Laravel Query Builder

I have a query and I want to add a collection using Laravel query builder.

Hotel::addSelect([
   'selectableLocations' => AllLocations::orderBy('name')->get()
])
  ->with('location')
  ->get();

Well, this returns:

SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters (SQL: select [{"id":1,"name":"John Avenue"},{"id":4,"name":"Ontirio Village"},{"id":2,"name":"Rovie"},{"id":3,"name":"Movie Lot"}] from dogs limit 100 offset 0)

I know this may seem like an anti-pattern but the reason I need this is because I have a datatable and want to show a select (dropdown) with AllLocations so that user can change in the datatable.

My idea is that I can do $dog->selectableLocations to see all locations. Because if I don’t do it like this, it will query for each row individually.

Is there a way to do that?


If I could achieve it like this, that’d be perfect.

$selectableLocations = AllLocations::get();

$hotels = Hotel::addSelect([
    'selectableLocations' => $selectableLocations
])
  ->with('location')
  ->get();

Advertisement

Answer

EDIT:

Because if I don’t do it like this, it will query for each row individually.

Since your primary concern is multiple queries, you could avoid db calls if you implement some sort of caching. Why not include the list as a custom attribute, load collection from cache? Like so:

public function getAllLocationsAttribute()
{
    return Cache::remember('all_locations', 30, function(){ //add remove seconds as required
        return AllLocatiobs::get();
    });
}

How about getting merging the two collections?

$hotels = Hotel::get();
$selectableLocations = AllLocations::get();
$hotels->put('selectableLocations', $selectableLocations);

Now, $hotels->selectableLocations will be a collection of AllLocations.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement