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;
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 want to combine two data search results into one array, I use array_merge but there is an array_merge() error:
Argument # 1 is not an array
How to turn $vendor's eloquent results into an array and combine it with $plucked?
$vendor = Vendor::find($id);
$vendor_detail = VendorDetail::where('vendor_id',$id)->get();
$plucked = $vendor_detail->pluck('vendor_profile_value','vendor_profile_name');
$coba = array_merge($vendor,$plucked);
$plucked already an array
I think the problem here is that $vendor is not yet an array
You could do it like this:
$vendor = Vendor::find($id);
$vendor_details = VendorDetail
::select('vendor_profile_value', 'vendor_profile_name')
->where('vendor_id', $id)
->get()
->toArray();
$coba = array_merge($vendor,$vendor_details);
The get() method execute the query returning a Collection instance, in which you can call the toArray() method.
Side note
As far as I can see, you could make use of relationships and eager loading.
If you have a one-to-many relationship defined like this in your Vendor model:
public function details()
{
return $this->hasMany(VendorDetails::class);
}
Then, you could eager load the relationship like this:
$vendor = Vendor::with('details')->find($id);
// ^^^^^^^^^^^^^^
You could even just load the wanted fields:
$vendor = Vendor::with('details:vendor_profile_value,vendor_profile_name')
->find($id);
Then, your object will have a new attribute called "details" containing the related objects (or a collection of the limited selected fields).
You can convert the $vendor to an Array like below.
$vendor = Vendor::find($id)->toArray();
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.
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 .
I'm trying to get a list of categories and return them as JSON for an AJAX call, but Laravel is including column names too, which I don't need.
$categories = Category::where('parent', '=', '0')->select('name')->get();
return response()->json($categories);
This way I get
[{"column_name", "value"}]
And I want
{"value1", "value2"}
Thanks!
Try this: $arr = json_decode($categories, true). Then deal with the array output it gives.
You simply use eloquent's lists method
$categories = Category::where('parent', '=', '0')->select('name')->lists('name');
return response()->json($categories);
Use array_values function to get the values array.
And {"value1", "value2"}the format is invalid of Json . Valid format ["value1","value2"] . If use { } means to Object ,but object must have key=>value.
$categories = Category::where('parent', '=', '0')->select('name')->get();
return response()->json(array_values($categories));