Laravel Eloquent get() indexed by primary key id - laravel

I often find it very useful to index my results by the primary key id.
Example:
$out = [];
$users = User::where('created_at', '>=', '2015-01-01')->get();
foreach ($users as $user) {
$out[$user->id] = $user;
}
return $out;
Is there anyway to do this in one shot with Eloquent? It's not useful to use the 0...n index.

You can accomplish this by using getDictionary() on your collection.
Like so:
$users = User::where('created_at', '>=', '2015-01-01')->get()->getDictionary();
Note: in newer version of Laravel (5.2+), getDictionary() was removed; keyBy() can be used instead:
$users = User::where('created_at', '>=', '2015-01-01')->get()->keyBy('id');

I created my own solution by having a super Model that extends Eloquent.
Full solution:
https://gist.github.com/yadakhov/741173ae893c1042973b
/**
* Where In Hashed by primary key
*
* #param array $ids
* #return array
*/
public static function whereInHash(array $ids, $column = 'primaryKey')
{
$modelName = get_called_class();
$primaryKey = static::getPrimaryKey();
if ($column === 'primaryKey') {
$column = $primaryKey;
}
$rows = $modelName::whereIn($column, $ids)->get();
$out = [];
foreach ($rows as $row) {
$out[$row->$primaryKey] = $row;
}
return $out;
}

Not with eloquent but this is potentially nicer option than looping through all the results.
$users = Users::all();
return array_combine($users->modelKeys(), $users);

You can use keyBy()
$users = User::where('created_at', '>=', '2015-01-01')->get()->keyBy('id')->toArray();

Related

Refactor Query Builder Laravel

I want to do repetitive get data and foreach on several tables (see example below). Is there a way to write the code in a cleaner way instead of repeating the same code for all the tables?
$xs = DB::table('table1')->where('text', 'like', '%string')->get();
foreach ($xs as $x) {
..
}
$ys = DB::table('table2')->where('text', 'like', '%string')->get();
foreach ($ys as $y) {
..
}```
My approach is using array and foreach
$tables = ['table1', 'table2'];
results = [];
foreach($tables as $table) {
$data = DB::table($table)->where('text', 'like', '%string')->get();
foreach($data as $d) {
// your logic here
}
$results[] = ; // return a value from each query to array
}
You can write a base function and pass tableName to it and execute certain action
public function getData($tableName) {
$query = DB::table($tableName)->where('text', 'like', '%string')->get();
foreach ($query as $row) {
...
}
// return result;
}
$tables = ['table1', 'table2', 'table3'];
$queryResponse = [];
foreach($tables as $tableName) {
$queryResponse[$tableName] = $this->getData($tableName);
}

Laravel 8 Paginate Collection (sortBy)

I try to paginate a sorted collection in Laravel 8, maybee any one have an idea?
That's my code:
$where = Business::where('name', 'LIKE', '%' . $what . '%');
$businesses = $where->get()->sortByDesc(function($business) {
return $business->totalReviews;
})->paginate(10); // <--- not working.. Collection::paginate not exists
Paginate can only be called on a builder instance (it makes no sense to call it on a collection as you already have all the data). But you are doing some logic based on the review count that requires a model method which must can only be called after fetching the data.
So you must refactor the ordering so that it gets called on the builder instance so that the ordering happens on SQL before the pagination logic happens.
withCount('relation') is perfect for this as it will append on a count of a specific relation onto your query which you can then sort by on SQL.
For example you can try this where reviews is a relation on the Business model that you have many of (likely either belongsToMany or hasMany):
Business::withCount('reviews')
->where('name', 'LIKE', '%' . $what . '%')
->orderBy('reviews_count', 'desc')
->paginate(10);
Where inside your Business model you have:
public function reviews()
{
return $this->hasMany(Review::class);
}
Remove the get:
$businesses = $where->sortByDesc(function($business) {
return $business->totalReviews;
})->paginate(10);
I fixed it on this way
$businesses = $where->get()->sortByDesc(function($business) {
return $business->getTotalReviews();
});
$businesses = ViewHelper::paginate($businesses, 10);
ViewHelper.class
<?php
namespace App\Classes;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Database\Eloquent\Collection;
class ViewHelper
{
/**
* Gera a paginação dos itens de um array ou collection.
*
* #param array|Collection $items
* #param int $perPage
* #param int $page
* #param array $options
*
* #return LengthAwarePaginator
*/
public static function paginate($items, $perPage = 15, $page = null, $options = [])
{
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
}

Laravel filter of multiple variables from multiple models

Goodmorning
I'm trying to make a filter with multiple variables for example I want to filter my products on category (for example 'fruit') and then I want to filter on tag (for example 'sale') so as a result I get all my fruits that are on sale. I managed to write seperate filters in laravel for both category and tag, but if I leave them both active in my productsController they go against eachother. I think I have to write one function with if/else-statement but I don't know where to start. Can somebody help me with this please?
These are my functions in my productsController:
public function productsPerTag($id){
$tags = Tag::all();
$products = Product::with(['category','tag','photo'])->where(['tag_id','category_id'] ,'=', $id)->get();
return view('admin.products.index',compact('products','tags'));
}
public function productsPerCategory($id){
$categories = Category::all(); //om het speciefieke id op te vangen heb ik alle categories nodig
$products = Product::with(['category','tag','photo'])->where('category_id', '=', $id)->get();
return view('admin.products.index',compact('products','categories'));
}
These are my routes in web.php. I guess this will also have to change:
Route::get('admin/products/tag/{id}','AdminProductsController#productsPerTag')->name('admin.productsPerTag');
Route::get('admin/products/category/{id}','AdminProductsController#productsPerCategory')->name('admin.productsPerCategory');
For filter both
change your URL like
Route::get('admin/products/tag/{tag_id?}/{category_id?}','AdminProductsController#productsPerTag')->name('admin.productsPerTag');
Make your function into the controller like
public function productsPerTag($tagId = null, $categoryId = null){
$tags = Tag::all();
$categories = Category::all();
$query = Product::with(['category','tag','photo']);
if ($tagId) {
$query->where(['tag_id'] ,'=', $tagId);
}
if ($tagId) {
$query->where(['category_id'] ,'=', $categoryId);
}
$products = $query->get();
return view('admin.products.index',compact('products','tags', 'categories'));
}
You are trying to filter in your query but you pass only 1 parameter to your controller, which is not working.
1) You need to add your filters as query params in the URL, so your url will look like:
admin/products/tag/1?category_id=2
Query parameters are NOT to be put in the web.php. You use them like above when you use the URL and are optional.
2) Change your controller to accept filters:
public function productsPerTag(Request $request)
{
$categoryId = $request->input('category_id', '');
$tags = Tag::all();
$products = Product::with(['category', 'tag', 'photo'])
->where('tag_id', '=', $request->route()->parameter('id'))
->when((! empty($categoryId)), function (Builder $q) use ($categoryId) {
return $q->where('category_id', '=', $categoryId);
})
->get();
return view('admin.products.index', compact('products', 'tags'));
}
Keep in mind that while {id} is a $request->route()->parameter('id')
the query parameters are handled as $request->input('category_id') to retrieve them in controller.
Hope It will give you all you expected outcome if any modification needed let me know:
public function productList($tag_id = null , $category_id = null){
$tags = Tag::all();
$categories = Category::all();
if($tag_id && $category_id) {
$products = Product::with(['category','tag','photo'])
->where('tag_id' , $tag_id)
->where('category_id' , $category_id)
->get();
} elseif($tag_id && !$category_id) {
$products = Product::with(['category','tag','photo'])
->where('tag_id' , $tag_id)
->get();
} elseif($category_id && !$tag_id) {
$products = Product::with(['category','tag','photo'])
->where('category_id' , $category_id)
->get();
} elseif(!$category_id && !$tag_id) {
$products = Product::with(['category','tag','photo'])
->get();
}
return view('admin.products.index',compact(['products','tags','products']));
}
Route:
Route::get('admin/products/tag/{tag_id?}/{category_id?}','AdminProductsController#productsPerTag')->name('admin.productsPerTag');

How to use transform in paginated collection in laravel

I want to use map or transform in paginated collection in laravel 5.5 but I am struggling it work
This is what I was trying to do but getCollection is not available in LengthAwarePaginator as what we used to do in previous laravel versions see: How to transform paginated collection
$query = User::filter($request->all()
->with('applications');
$users = $query->paginate(config('app.defaults.pageSize'))
->transform(function ($user, $key) {
$user['picture'] = $user->avatar;
return $user;
});
This is what I receive but there is no pagination details in my result
How can I return transformed collection with pagination details?
For Laraval >= 8.x: if you want to perform the transform() on the collection of the paginated query builder result instead of doing the pagination on the full collection, one can use the method through():
User::filter($request->all()
->with('applications')
->paginate(config('app.defaults.pageSize'))
// through() will call transform() on the $items in the pagination object
->through(function ($user, $key) {
$user['picture'] = $user->avatar;
return $user;
});
I have ended up building custom paginate function in AppServiceProvider
use Illuminate\Support\Collection;
In register of AppServiceProvider
Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPage($pageName);
return new \Illuminate\Pagination\LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
You should paginate before retrieving the collection and transforming as follows:
$query = User::filter($request->all())->with('applications')->paginate(50);
$users = $query->getCollection()->transform(function ($user, $key) {
//your code here
});
dd($users);
It should give you your desired result.
Your problem is that you are printing the $users variable that hold the array of the users in the current page. To get the paginated list try to return/print $query instead.
So your code should be as following:
$query = User::filter($request->all()
->with('applications');
$users = $query->paginate(config('app.defaults.pageSize'))
->transform(function ($user, $key) {
$user['picture'] = $user->avatar;
return $user;
});
return response()->json($query);
Happy Coding!
You can use method setCollection from Paginator class:
https://laravel.com/api/8.x/Illuminate/Pagination/Paginator.html#method_setCollection
$messages = $chat->messages()->paginate(15);
$messages->setCollection($messages->getCollection()->transform(function($item){
$item->created = $item->created_at->formatLocalized('%d %B %Y %H:%M');
return $item;
}));

how can i notify a specific users

here is my AdsController.php
public function save(Request $request)
{
$this ->validate($request,[
'object'=>'required',
'description'=>'string',
]);
$ads = new Ad;
$current_user=Auth::user();
$ads->object = $request->input('object');
$ads->description = $request->input('description');
$ads->save();
$users = User::where(("id","!=",$current_user->id ) || ("admin","=",1 ))->get();
foreach ($users as $user) {
$user->notify(new NewAd($current_user, $ads));
}
return redirect('listads') ;
}
I want to post an ad to the admin only but i have an error
Please help me
You made a simple mistake of your query builder, the conditions should be chained as follow:
$users = User::where('id', '<>', $current_user->id)->where('admin', 1)->get();
Use where condition like this
$users = User::where("id","!=",$current_user->id)
->orWhere("admin",1 )->get();

Resources