Laravel has a method returens a response like key=>value array.
$users = User::lists('name', 'id')->all();
if I want to customize lists to return key as a combination of name and username, how shoud i code ?
I also tried
$users = User::lists('name'.'username', 'id')->all();
but, it's not working :|
Is there an alternative method ?
There is no custom pluck() method (do not use lists() since it's deprecated). But you can create your own helper or method using this code:
$allUsers = User::all();
$users = [];
foreach ($allUsers as $user) {
$users[$user->id] = $user->name.' '.$user->username;
}
Try this,
$users = User::lists('name', 'id');
try this,
$users = User::pluck('name','id');
As, in laravel 5.2.0 lists() method was deprecated, it was replaced by pluck method .
Related
Below is my controller code
$category_ids = array();
foreach($categories as $category){
$category_ids[] = $category->id;
}
$paginated_products = Product::where('status',1)->whereIn('category_id',$category_ids)->latest()->paginate(30);
Below is my blade view code
$first_ten_products = array_slice($paginated_products,0,9);
But am getting the error below how can i fix it. Thanks
array_slice(): Argument #1 ($array) must be of type array, Illuminate\Pagination\LengthAwarePaginator given
Your error is saying that $paginated_products is not an Array, and array_slice requires an Array to function. You can use ->toArray() as suggested in the comments/your answer, but there are also Laravel Collection methods for this:
$paginatedProducts = Product::where('status', 1)
->whereIn('category_id', $categories->pluck('id'))
->latest()
->paginate(30);
$chunkedProducts = $paginatedProducts->getCollection()->chunk(10);
Some changes:
Use ->pluck('id') instead of foreach()
The pluck() Method returns a Collection of the speicified values, and is a short-hand for what your foreach($models as $model) { $array[] = $model->id } accomplishes.
Define $chunkedProducts from your Paginated Product Models
->paginate(30) returns an instance of a LengthAwarePaginator, which has a method getCollection(), which can then be chained to the chunk() method. chunk(10) will return a Collection with X elements. In your case:
$firstTenProducts = $chunkedProducts[0];
$secondTenProducts = $chunkedProducts[1];
$thirdTenProducts = $chunkedProducts[2];
It would probably make more sense to pass these to the Frontend and loop them, like:
#foreach($chunkedProducts as $chunkOfTen)
<!-- Do something with each group of 10 Products -->
#endforeach
But you can use the chunks however you see fit, and however works with your project.
If I have refactored my code as below and it worked
$first_ten_products = array_slice($paginated_products->toArray(),0,9);
dd($first_ten_products['data']);
I just added the data property as above in the dd method and it worked
i tried to use pagination in my laravel view i got this problem
Method Illuminate\Database\Eloquent\Collection::links does not exist. (View: C:\wamp\www\project\resources\views\demmande\demmandes.blade.php)
here is my controller function
public function ViewDemmandes(){
$listdemmande=Demmande::paginate(10)->sortByDesc('created_at');
$listvillee=Ville::all();
$listcategorie=Categorie::all();
$villes = $listvillee;
$demmande = $listdemmande;
$categorie = $listcategorie;
return view("demmande.demmandes",compact('villes','categorie','demmande'));
}
but when i delete sortByDesc function like this
public function ViewDemmandes(){
$listdemmande=Demmande::paginate(3);
$listvillee=Ville::all();
$listcategorie=Categorie::all();
$villes = $listvillee;
$demmande = $listdemmande;
$categorie = $listcategorie;
return view("demmande.demmandes",compact('villes','categorie','demmande'));
}
it works fine please can you help me resolve this problem
The ->paginate(10) will return an instance of LengthAwarePaginator. Which implements all the methods the Collection has (->sortByDesc() being one of them). But calling a collection method will return the underlying collection, not an instance of paginator.
So in your case you're overriding the paginator with the collection being returned from ->sortByDesc().
Sort with SQL instead of on a collection:
$listdemmande = Demmande::orderBy('created_at', 'DESC')->paginate(10);
// Or using `->latest()` shorthand:
// $listdemmande = Demmande::latest()->paginate(10);
If there's a reason why you want to sort after fetching the query, you could override just the paginators underlying collection:
$listdemmande = Demmande::paginate(10);
$listdemmande->setCollection($listdemmande->sortByDesc('created_at'));
You can use like this in controller
$listdemmande=Demmande::orderBy('created_at', 'desc')->paginate(10);
And also don't forget to add in blade view to add this ...
After foreach add to this
{{$listdemmande->links()}}
Your links error is solve.
I'm trying to send an email to multiple emails, so I did a query to my users tables but the result is an array with keys that don't work mail->to().
I need an array like this: $owners = ['myoneemail#esomething.com', 'myother#esomething.com','myother2#esomething.com']; from database.
My query:
$owners = DB::table('users')->select('email')->where('active', 1)->where('userType', 1)->get();
I also try use ->toArray() but comes with keys.
Email:
Mail::send('email-view', $data, function($message) use ($data, $owners)
{
$message->from('no-reply#email.pt' , 'FROM');
$message->to($owners)->subject('subject');
});
$owners = DB::table('users')->where('active', 1)->where('userType', 1)->pluck('email')->toArray();
You can use ->pluck(), like this:
$owners = DB::table('users')->select('email')->where('active', 1)->where('userType', 1)->get();
$emailList = $owners->pluck('email');
$owners = DB::table('users')->where('active', 1)->where('userType', 1)->pluck('email');
or
$owners = User::where('active', 1)->where('userType', 1)->pluck('email');
here User is your model name
First of all, the where condition is not proper in your query builder code.
It has to be like:
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
You can use pluck() to get the list in Laravel 5.
All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:
foreach ($owners as $owner) {
echo $owner->filed_name;
echo $owner->filed_name;
...
}
There is no restriction for using the core PHP code while using a PHP framework. You may refer the official PHP Arrays Manual page to work with the language construct.
If you need to convert JSON to array, use:
json_decode($owners);
I have a piece of code like this:
$products = Product::all()
if ($search_value) {
$products = $products->where('name', 'LIKE', "%$search_value%");
}
$products = $products->orderBy('created_at', 'desc')->skip(10)->take(10)->with('tags')->get();
I got the following error:
BadMethodCallException in Macroable.php line 81:
Method orderBy does not exist.
I guess orderBy need to follow Product:: directly, but I can't save $products = Product::, can I?
Any suggestions? Thanks.
You're trying to use orderBy() method on Eloquent collection. Try to use sortByDesc() instead.
Alternatively, you could change $products = Product::all(); to $products = new Product();. Then all your code will work as you expect.
just use the one line code it will work fine
$product= Product::orderBy('created_at','desc')->get();
use sortByDesc('id') or simple sortBy() inside use the variable through which you wanna sort like i add id
If you want to get the list of all data and grab it in descending order try this:
$post = Post::orderBy('id', 'DESC')->get();
You are first getting all() data and then trying to sort which is wrong. You have to fix this by removing
$products = Product::all()
and changing your code into something like this
if ($search_value) {
$products = Product::where('name', 'LIKE', "%$search_value%");
}
else {
$products = Product::orderBy('created_at', 'desc')->skip(10)->take(10)->with('tags')->get();
}
Hope you get idea to tweak your code.
Your query is wrong.
remove all from $products = Product::all() and then put get() at the end of your query.
$table_Data = DB::table('tbl_product')->orderBy('id','DESC');
You can use this...
I have a controller where I want to combine data from multiple tables with parallel structures. What I want to end up with in the end is one object I can return from the controller so I can parse it in Backbone.
I want to do something like this:
public function index()
{
$mc = MainContact::where('verified', '=', '1')->get();
$sm = SendMessage::where('verified', '=', '1')->get();
$obj = (object) array_merge((array) $mc, (array) $sm);
return $obj;
}
I'm told by another post on StackOverflow that this works in PHP 5.3+. However, this returns the following error in Laravel:
UnexpectedValueException: The Response content must be a string or object implementing
__toString(), "object" given.
How do I implement this method in Laravel? Both $mc and sm return valid objects in Laravel.
Nowadays you can use
$new_collection = $collection->merge($other_collection).
This works in Laravel 4 and seems to handle both arrays and collections.
What you can do here is merge the arrays of the two query result and then use the Response with json output like shown below.
$array = array_merge($mc->toArray(), $sm->toArray());
return Response::json($array);
We can use collection as below
$admins = User::where('type', '=', 'admin')->get();
$authors = User::where('type', '=', 'author')->get();
$admin_author_collection = $admins->merge($authors);
Also, Please refer the various collection methods to below link
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html
Route::get('test', function(){
$rank = Rank::get();
$policy = Policy::get();
$obj = (object)array_merge_recursive((array)$rank , (array)$policy);
var_dump($obj);
});
This is working for me. Instead of array_merge use array_merge_recursive().
You could simply use array_merge(firstObject,secondObject) function.
$obj = array_merge($mc, $sm);
return $obj;