Unserialize cart data not working Laravel - 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.

Related

Cache eloquent model with all of it's relations then convert it back to model with relations?

I am trying to optimize a project that is working pretty slow using caching. I'm facing a problem that I don't quite understand how to cache full eloquent models with their relationships and later on covert them back to a model with all relations intact. Here's a fragment of my code
if (Cache::has($website->id.'_main_page')) {
$properties = (array) json_decode(Cache::get($website->id.'_main_page'));
$page = Page::hydrate($properties);
}else{
$expiresAt = now()->addMinutes(60);
$page = Page::with(['sections', 'pageSections.sectionObjects'])->where('website_id', $website->id)->where('main', 1)->first();
Cache::put($website->id.'_main_page', $page->toJson(), $expiresAt);
}
Problem is, hydrate seems to be casting this data as a collection when in fact it's suppose to be a single model. And thus later on I am unable to access any of it's properties without getting errors that they don't exists. $properties variable looks perfect and I would use that but I need laravel to understand it as a Page model instead of stdClass, I also need all of the relationships to be cast into their appropriate models. Is this even possible? Any help is much appreciated
Is there any reason you can't use the cache like this
$page = Cache::remember($website->id.'_main_page', 60 * 60, function () use ($website) {
return Page::with(['sections', 'pageSections.sectionObjects'])
->where('website_id', $website->id)
->where('main', 1)
->first();
});
Conditional
$query = Page::query();
$key = $website->id.'_main_page';
if (true) {
$query = $query->where('condition', true);
$key = $key . '_condition_true';
}
$query::with(['sections', 'pageSections.sectionObjects'])
->where('main', 1)
$page = Cache::remember($key, 60 * 60, function () use ($query) {
return $query->first();
});

Laravel 5: fresh() on a model doesn't work in PHPUnit

What I've been trying is to reload a model in testing.
I've been using fresh(), which doesn't work in testing for some reason. (Possibly this is a bug)
Here is a snippet.
//There is a relationship between Order and OrderItem.
//One Order hasMany OrderItem
$order = factory(Order::class)->create([...]);
$orderItem = factory(OrderItem::class)->create([
'order_id' => $order->id,
]);
$response = $this->delete('/api/order/' . $order->id);
$response->assertResponseStatus(200);
//This passes.
$orderItem = $orderItem->fresh();
$this->assertEquals($orderItem->some_attribute, 0);
The last line results in trying to get property of non-object.
I changed
$orderItem = $orderItem->fresh();
into
$orderItem->fresh();
This approach didn't refresh $orderItem at all.
Do you see anything I'm doing wrong?
Any advice will be appreciated.
PS
$orderItem = OrderItem::find($orderItem->id);
I tried this approach, which resulted in trying to get property of non-object as well.
factory() return the instance of Illuminate\Database\Eloquent\Factory
it does not have any fresh() method implemented in it.
Model has an implementation of fresh() method.
fresh(array|string $with = []) //Reload a fresh model instance from the database.
and
OrderItem::find($orderItem->id);
returns collection.
Here is what you can do.
OrderItem::where('id', $orderItem->id)->fresh();
reference:
https://laravel.com/api/5.6/Illuminate/Database/Eloquent/Factory.html
Hope this helps

how to put and retrieve laravel collection object on Session

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.

filtering a paginated eloquent collection

I am trying to filter a paginated eloquent collection, but whenever I use any of the collection methods, I lose the pagination.
$models = User::orderBy('first_name','asc')->paginate(20);
$models = $models->each(function($model) use ($filters) {
if(!is_null($filters['type'])) {
if($model->type == $filters['type'])
return $model;
}
if(!is_null($filters['state_id'])) {
if($model->profile->state_id == $filters['state_id'])
return $model;
}
if(!is_null($filters['city_id'])) {
if($model->profile->city_id == $filters['city_id'])
return $model;
}
});
return $models;
I am working with Laravel 4.2, is there any way to persist the pagination?
An answer to the titular question, which is possible in Laravel 5.2+:
How to filter the underlying collection of a Paginator without losing the Paginator object?
You can eject, modify and inject the collection as follows:
$someFilter = 5;
$collection = $paginator->getCollection();
$filteredCollection = $collection->filter(function($model) use ($someFilter) {
return $model->id == $someFilter;
});
$paginator->setCollection($filteredCollection);
The Paginator is built on an underlying collection, but indeed when you use any of the inherited Collection methods they return the underlying collection and not the full Paginator object: collection methods return collections for chaining together collection calls.
Expanding on mininoz's answer with your specific case:
//Start with creating your object, which will be used to query the database
$queryUser = User::query();
//Add sorting
$queryUser->orderBy('first_name','asc');
//Add Conditions
if(!is_null($filters['type'])) {
$queryUser->where('type','=',$filters['type']);
}
if(!is_null($filters['state_id'])) {
$queryUser->whereHas('profile',function($q) use ($filters){
return $q->where('state_id','=',$filters['state_id']);
});
}
if(!is_null($filters['city_id'])) {
$queryUser->whereHas('profile',function($q) use ($filters){
return $q->where('city_id','=',$filters['city_id']);
});
}
//Fetch list of results
$result = $queryUser->paginate(20);
By applying the proper conditions to your SQL query, you are limiting the amount of information that comes back to your PHP script, and hence speeding up the process.
Source: http://laravel.com/docs/4.2/eloquent#querying-relations
I have a scenario that requires that I filter on the collection, I cannot rely on the Query Builder.
My solution was to instantiate my own Paginator instance:
$records = Model::where(...)->get()->filter(...);
$page = Paginator::resolveCurrentPage() ?: 1;
$perPage = 30;
$records = new LengthAwarePaginator(
$records->forPage($page, $perPage), $records->count(), $perPage, $page, ['path' => Paginator::resolveCurrentPath()]
);
return view('index', compact('records'));
Then in my blade template:
{{ $records->links() }}
paginate() is function of Builder. If you already have Collection object then it does not have the paginate() function thus you cannot have it back easily.
One way to resolve is to have different builder where you build query so you do not need to filter it later. Eloquent query builder is quite powerful, maybe you can pull it off.
Other option is to build your own custom paginator yourself.
You can do some query on your model before do paginate.
I would like to give you some idea. I will get all users by type, sort them and do paginate at the end. The code will look like this.
$users = User::where('type', $filters['type'])->orderBy('first_name','asc')->paginate(20);
source: http://laravel.com/docs/4.2/pagination#usage
This was suitable for me;
$users = User::where('type', $filters['type'])->orderBy('first_name','asc')->paginate(20);
if($users->count() < 1){
return redirec($users->url(1));
}
A workaround when mixing search parameters and pagination, since default pagination won't keep the search parameters, using GET:
$urlSinPaginado = url()->full();
$pos=strrpos(url()->full(), 'page=');
if ($pos) {
$urlSinPaginado = substr(url()->full(), 0, $pos-1);
}
[...]
->paginate(5)
->withPath($urlSinPaginado);
sample generated pagination link: http://myhost/context/list?filtro_1=5&filtro_2=&filtro_3=&filtro_4=&filtro_5=&filtro_6&page=8
You can simply use this format in views
{!! str_replace('/?', '?', $data->appends(Input::except('page'))->render()) !!}
For newer versions of Laravel, you can use this:
$data->paginate(15)->withQueryString();

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