Laravel pluck an array from nested relationship - laravel

I need to get only the roomnumber arrays returned from the following query:
$roomnumbers = Room::with(['floorroomcount' => function($query){
$query->with('roomnumber')->get();
}])->where('roomtype_id', $roomtype_id)->get();
Tried:
The follow pluck is returning floorroomcount
$roomnumbers->pluck('floorroomcount');
but i need roomnumber array, how can i get?

This gives you all roomnumber results in one collection:
$roomnumbers->pluck('floorroomcount')->collapse()->pluck('roomnumber')->collapse();

You may shorten #Jonas Staudenmeir's answer like so:
$roomnumbers->pluck('floorroomcount.*.roomnumber.*')->collapse();
pluck('*') is essentially the same as collapse() in this particular context.

This is working, but with many loop and echoing directly, if anything can be simplified please let me know :
$roomnumbers = Room::with(['floorroomcount.roomnumber'])->where('roomtype_id', $roomtype_id)->get();
$floorroomcounts = $roomnumbers->pluck('floorroomcount');
$records = $floorroomcounts->map(function($floorroomcount, $value){
return $floorroomcount->pluck('roomnumber')->flatten();
})->values()->all();
foreach($records as $record){
foreach($record as $row){
echo '<option value='.$row->id.'>'.$row->roomnumber.'</option>';
}
}
//return response()->json($roomnumbers);

Try,
$roomnumbers = Room::with(['floorroomcount' => function($query){
$query->with('roomnumber')->get();
}])
->where('roomtype_id', $roomtype_id)
->get();
$records = $roomnumbers->map(function($element, $value){
return $element->map(function($e, $v){
return $e->roomnumber;
});
})->values()->all();
map() is a Laravel collection method so you need to import the collection facade on the top of the controller like: use Illuminate\Support\Collection;

In Laravel 5.1 and + you can use flatten() on collection.
method flattens a multi-dimensional collection into a single dimension:
$roomnumbers->flatten()->pluck('floorroomcount');

Related

GroupBy from relations using laravel eloquent

I have TypeOfVehicle model that has many Vehicle.
How can I group all vehicles by type of vehicle name with counts to get something like this
[
'Sedan' => 10,
'SUV' => 25,
'Crossover' => 5
]
I assume you have eloquent relation type in Vehicle model, e.g.:
public function type()
{
return $this->belongsTo('\App\TypeOfVehicle');
}
So, you can get you data this way:
$result = Vehicle::select('vehicle_type_id', DB::raw('count(vehicle_type_id) as cnt'))
->with('type') // with your type relation
->groupBy('vehicle_type_id') // group by type of vehicle
->get() // get collection from database
->pluck('cnt', 'type.name') // get only needful data
->toArray(); // cast to array if necessary
You can use
$counts = DB::table('tablename')
->select('TypeOfVehicle', DB::raw('count(*) as total'))
->groupBy('TypeOfVehicle')
->get();
Counting Related Models
If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models.
$typeOfVehicles = App\TypeOfVehicle::withCount('vehicles')->get();
foreach ($typeOfVehicles as $typeOfVehicle) {
echo $typeOfVehicle->vehicles_count;
}
Try this it gives you your solution
$vehicle=Vehicle::all();
$grouped = $vehicle->groupBy(function ($item, $key) {
return substr($item['that_coloumn_name_like_type'], 0);
});
$groupCount = $grouped->map(function ($item, $key) {
return collect($item)->count();
});
//dd($groupCount); to check it work correctly

Laravel simplePaginate() for Grouped Data

I have the following query.
$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy(function ($project) {
return Carbon::parse($project->created_at)->format('Y-m-d');
})->simplePaginate(5);
When I try to paginate with the simplePaginate() method I get this error.
stripos() expects parameter 1 to be string, object given
How can I paginate grouped data in this case?
The created_at attribute is already casted as a Carbon Object (by default in laravel models). that's why you are getting that error. Try this:
$projects = Project::orderBy('created_at', 'desc')->get();
$data['sorted'] = $projects->groupBy(function ($project) {
return $project->created_at->format('Y-m-d');
})->simplePaginate(5);
this answer is just for the error you're getting. now if you want help with the QueryBuilder, can you provide an example of the results you're expecting to have and an example of the database structure ?
The pagination methods should be called on queries instead of collection.
You could try:
$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy('created_at');
The problem was solved. I was create custom paginator via this example:
https://stackoverflow.com/a/30014621/6405083
$page = $request->has('page') ? $request->input('page') : 1; // Use ?page=x if given, otherwise start at 1
$numPerPage = 15; // Number of results per page
$count = Project::count(); // Get the total number of entries you'll be paging through
// Get the actual items
$projects = Project::orderBy('created_at', 'desc')
->take($numPerPage)->offset(($page-1)*$numPerPage)->get()->groupBy(function($project) {
return $project->created_at->format('Y-m-d');
});
$data['sorted'] = new Paginator($projects, $count, $numPerPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
simplePaginate Method is exist in the path below:
Illuminate\Database\Eloquent\Builder.php::simplePaginate()

Can I put a collection or array into the where clause on laravel eloquent?

$collection=["c","a","f","h","j","o","k"]
$total_sums=Models::select('count')->whereIn('class',['c','a','f','h','j','o','k'])
->get()
->sum('count');
can I use variable $collection like this?
$total_sums=Models::select('count')->whereIn('class',[''.$collection.''])
->get()
->sum('count');
You can use both.
whereIn() accepts both Array and a Collection.
You just simply pass it as a second parameter.
$array = ["c","a","f","h","j","o","k"];
$collection = collect($array);
$total_sums=Models::select('count')->whereIn('class', $array)
->get()
->sum('count');
// works
$total_sums=Models::select('count')->whereIn('class', $collection)
->get()
->sum('count');
// also works!
No because $collection is already an array. When you try to concatenate it to a string, I believe your query will look like the following...
select count from models where class in ('Array');
What you probably actually want to do is...
->whereIn('class', $collection)

database query not working properly laravel

I have a database query as below:
$data = DB::table('settings')->select('value')->where('name', '=', $name)->get();
echo $data["value"];
but it gives error:
Undefined index: value
if I echo $data; then I get below result:
[{"value":"theme_default"}]
get() returns a Laravel Collection object, which has magic methods to turn itself into a string when you try to use it as such (like with an echo statement). As you can see in the JSON that you've printed, $data is an array or collection of objects, so you want the first one in the collection before trying to get the value:
$row = $data->first();
echo $row->value;
Try this:
$data = DB::table('settings')->select('value')->where('name', '=', $name)->first();
echo $data["value"];
//or
echo $data->value;
You can turn the result into an array like this:
$data = DB::table('settings')
->select('value')
->where('name', '=', $name)
->get()
->toArray();
//then use the value of the first element
dd(#$data[0]['value']);
, but I strongly suggest that you use the Laravel Collection in order to make use of its powerful methods.

Laravel Eloquent "WHERE NOT IN"

I'm having trouble to write query in laravel eloquent ORM.
my query is
SELECT book_name,dt_of_pub,pub_lang,no_page,book_price
FROM book_mast
WHERE book_price NOT IN (100,200);
Now I want to convert this query into laravel eloquent.
Query Builder:
DB::table(..)->select(..)->whereNotIn('book_price', [100,200])->get();
Eloquent:
SomeModel::select(..)->whereNotIn('book_price', [100,200])->get();
You can use WhereNotIn in following way also:
ModelName::whereNotIn('book_price', [100,200])->get(['field_name1','field_name2']);
This will return collection of Record with specific fields
I had problems making a sub query until I added the method ->toArray() to the result, I hope it helps more than one since I had a good time looking for the solution.
Example
DB::table('user')
->select('id','name')
->whereNotIn('id', DB::table('curses')->select('id_user')->where('id_user', '=', $id)->get()->toArray())
->get();
Query Builder:
DB::table('book_mast')
->select('book_name','dt_of_pub','pub_lang','no_page','book_price')
->whereNotIn('book_price', [100,200])->get();
Eloquent:
BookMast::select('book_name','dt_of_pub','pub_lang','no_page','book_price')
->whereNotIn('book_price', [100,200])->get();
The dynamic way of implement whereNotIn:
$users = User::where('status',0)->get();
foreach ($users as $user) {
$data[] = $user->id;
}
$available = User::orderBy('name', 'DEC')->whereNotIn('id', $data)->get();
You can use this example for dynamically calling the Where NOT IN
$user = User::where('company_id', '=', 1)->select('id)->get()->toArray();
$otherCompany = User::whereNotIn('id', $user)->get();
You can use WhereNotIn in the following way:
$category=DB::table('category')
->whereNotIn('category_id',[14 ,15])
->get();`enter code here`
You can do following.
DB::table('book_mast')
->selectRaw('book_name,dt_of_pub,pub_lang,no_page,book_price')
->whereNotIn('book_price',[100,200]);
Its simply means that you have an array of values and you want record except that values/records.
you can simply pass a array into whereNotIn() laravel function.
With query builder
$users = DB::table('applications')
->whereNotIn('id', [1,3,5])
->get(); //will return without applications which contain this id's
With eloquent.
$result = ModelClassName::select('your_column_name')->whereNotIn('your_column_name', ['satatus1', 'satatus2']); //return without application which contain this status.
This is my working variant for Laravel 7
DB::table('user')
->select('id','name')
->whereNotIn('id', DB::table('curses')->where('id_user', $id)->pluck('id_user')->toArray())
->get();
$created_po = array();
$challan = modelname::where('fieldname','!=', 0)->get();
// dd($challan);
foreach ($challan as $rec){
$created_po[] = array_push($created_po,$rec->fieldname);
}
$data = modelname::whereNotIn('fieldname',$created_po)->orderBy('fieldname','desc')->with('modelfunction')->get();
or try pluck in laravel
here
DB::table('user')
->select('id','name')
->whereNotIn('id', DB::table('curses')->where('id_user', '=', $id)->pluck('user_id'))
->get();

Resources