how to put and retrieve laravel collection object on Session - laravel

I know that we can insert array in Session as Session::push('person.name','torres') but how to keep laravel collection object such as $product = Product::all();,as like Session::put('product',$product);.Ho wto achieve this?

You can put any data inside the session, including objects. Seeing as a Collection is just an object, you can do the same.
For example:
$products = Product::all();
Session::put('products', $products);
dd(Session::get('products'));
Should echo out the collection.

You should convert it to a plain array, then convert them back to models:
Storing in the session
$products = Product::all()->map(function ($product) {
return $product->getAttributes();
})->all();
Session::put('products', $products);
Retrieving from the session
$products = Product::hydrate(Session::get('products'));
You can see an example of this method here.

Related

How to get a value from database on Laravel Controller?

I have this code where I want to select certain values from the table. Counter is my Model.
$today = '2022-03-16';
$tanggal = Counter::select('tanggal')->where('api', 'Agenda')->where('tanggal', $today)->get();
But if i dd($tanggal->tanggal), it returns with an error Property [tanggal] does not exist on this collection instance.
How to get a value from 'tanggal' attribute?
You are using get() method. it will return collection. You can not access any field directly from collection.
You have to need use freach loop to access single property.
$today = '2022-03-16';
$tanggals = Counter::select('tanggal')
->where('api', 'Agenda')->where('tanggal', $today)->get();
forech( $tanggals as $tanggal)
{
dump($tanggal->tanggal);
}
You are trying to access a model property from a Collection, this can be fixed like so:
$tanggal = Counter::where(['api' => 'Agenda', 'tanggal' => $today])->first(['tanggal']);
get() returns a Collection, first() returns a Model.
You can use the collection but then use its .each() method and give it a lambda instead to process each value.
$collection = Counter::select('tanggal')->where('api', 'Agenda')->where('tanggal', $today)->get();
$collection->each(function ($item, $key) {
//write now your code here can do $item->tanggal
});

Unserialize cart data not working Laravel

I'm save my cart products as unserialized data from my cart session.
$order = new Order();
$order->cart = serialize($cart);
$order->code = strtoupper(str_random(15));
$order->user_id = Auth::user()->id;
$order->save();
now i need to unserialize the data to use it in my blade file, this is the function i'm using
$orders = Order::with('user')->findOrFail($order->id);
$orders->transform(function($order, $key){
$order->cart = unserialize($order->cart);
return $order;
});
dd($orders);
I'm getting this error
BadMethodCallException Call to undefined method App\Order::transform()
what seems to be the problem? and how can i unserialize my data;
any ideas ???
With findOrFail you retrieve just one instance of model, not a collection.
$orders = Order::with('user')->findOrFail($order->id);
Also what is $order->id you have your order model?
So
$order->load('user');
$order->cart = unserialize($order->cart);
Or do you want a collection then your code will work like this
$orders = Order::with('user')->get();
$orders->transform(function($order, $key) {
$order->cart = unserialize($order->cart);
return $order;
});
The problem is not about unserialize, it doesn't even get there. The problem seems to be related to an undefined method you are trying to use ($orders->transform).
Can you please provide the code in your Order class? Did you define the transform method there?
EDIT:
by using serialize you are kinda' missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries.
Also, many tests prove that json_encode is faster than serialize.

collections and eloquent results

I have a set of row returned from a function and stored in a variable called $topics. Each topic contains a set of articles. so for the variable $topics if we do $topics[0]->articles we get several articles, and if we do $topics[1]->articles we get another set of articles. What i want to do is to put all these articles in one variable lets call it $articles so that I can do operations such as
$articles->where('author', 'Jone Doe')->get();
I tried to do this:
$articles = new collection();
foreach( $topics as $topic) {
foreach( $topic->articles as $article)
$articles->push($article);
But this unfortunately destroys the actual structure of the articles. like I can't do $articles->translations where i use a translation package. but i can do $topics[0]->articles->translations. basically i want to get all the articles in one collection as if they were returned from doing something like
$articles = Article::all()->get();
Thanks
Just use the pluck method on your collection
$articles = $topics->pluck('articles');
And if you wish a 1-dimension articles collection
$articles = $topics->flatMap(function ($topic) {
return $topic->articles;
});

Eloquent Return Non Associative Array?

I am trying to get an array list of IDs to pass onto another model query.
$companies = $user->companies->pluck('id');
But it keeps returning an associative array as such:
[ 0 => 2, 1 => 9]
So when I pass it to the find method on my Company model, like this
$company = Company::find($companies);
I get the following error:
Trying to get property of non-object
I need to be able to pass a non-associative array to the call like such:
Company::find([2,9]);
Try that:
$companies = $user->companies->pluck('id')->toArray();
Just did a test in tinker and the result is a flat array, the "find" will work for sure!
As you can see in Laravels source code
src/Illuminate/Database/Eloquent/Builder.php
public function find($id, $columns = ['*'])
{
if (is_array($id)) {
return $this->findMany($id, $columns);
}
$this->query->where($this->model->getQualifiedKeyName(), '=', $id);
return $this->first($columns);
}
find() will internally call findMany() if the first parameter is an array. But $user->companies->pluck('id') returns a Collection and the Builder creates a wrong query. So your options are:
Use findMany():
$company = Company::findMany($companies);
Convert the Collection to an array:
$company = Company::find($companies->toArray());
Use whereIn():
$company = Company::whereIn('id', $companies)->get();
But actually that all doesn't seem to make any sense, because $user->companies probably already contains the collection you want to fetch from DB. So you could also write:
$company = $user->companies;
However - the fact that you are using singular naming (company) for a set of companies, let me think that you are trying to achieve something completely different.
You can try with the whereIn method
Company::whereIn('id', $companies)->get();

Returning array of objects in Laravel

I need to be able to change objects on server, save those, and return results back to frontend part of application.
So basically, I have some code that does manipulation of data, than Eloquent that does saving, and than I want to return Eloquent object back. Problem is that I have more than one object, that I'll manipulate, and right now, I'm putting all of them in array. When it comes back to my frontend all it has is this:
[{"incrementing":true,"timestamps":true,"exists":true}]
Here is the simplified code:
$results = array();
foreach ($tasks as $task){
//some manipulation
$result = Task::find($task['id']);
$result->order = $task['order'];
$result->save();
$results[] = $result;
}
return Response::json($results);
Ok, the solution was to call toArray() method before putting element to array.
$results[] = $result->toArray();

Resources