Reputation: 429
When I go to store a dataset in Laravel, I sometimes get this error and haven't found a solution to it.
Serialization of 'Closure' is not allowed
Open: ./vendor/laravel/framework/src/Illuminate/Session/Store.php
*/
public function save()
{
$this->addBagDataToSession();
$this->ageFlashData();
$this->handler->write($this->getId(), serialize($this->attributes));
$this->started = false;
Here is the function being called when the error occurs:
public function store()
{
$data = Input::all();
$validator = array('first_name' =>'required', 'last_name' => 'required', 'email' => 'email|required_without:phone', 'phone' => 'numeric|size:10|required_without:email', 'address' => 'required');
$validate = Validator::make($data, $validator);
if($validate->fails()){
return Redirect::back()->with('message', $validate);
} else {
$customer = new Customer;
foreach (Input::all() as $field => $value) {
if($field == '_token') continue;
$customer->$field = $value;
}
$customer->save();
return View::make('admin/customers/show')->withcustomer($customer);
}
}
What is causing this serialization error?
Upvotes: 2
Views: 6324
Reputation: 146191
Just replace following line:
return Redirect::back()->with('message', $validate);
with this:
return Redirect::back()->withErrors($validate);
Also, you may use something like this (To repopulate the form with old values):
return Redirect::back()->withErrors($validate)->withInput();
In the view
you can use $errors
variable to get the error messages, so if you use $errors->all()
then you'll get an array of error messages and to get a specific error you may try something like this:
{{ $errors->first('email') }} // Print (echo) the first error message for email field
Also, in the following line:
return View::make('admin/customers/show')->withcustomer($customer);
You need to change the dynamic method to withCustomer
not withcustomer
, so you'll be able to access $customer
variable in your view
.
Upvotes: 9
Reputation: 24661
return Redirect::back()->with('message', $validate);
You are telling Laravel to serialize the entire validator object into session. To redirect with errors, use the withErrors
method:
return Redirect::back()->withErrors($validate);
This will take the error messages out of the validator and flash those to session prior to redirecting. The way you're doing it now you're trying to store the entire class in Session which is causing your error.
Another issue I see is that I don't think there's a withcustomer
method on the View
class:
return View::make('admin/customers/show')->withcustomer($customer);
Try changing that to either just with
:
return View::make('admin/customers/show')->with('customer', $customer);
or make sure to capitalize the Customer
portion:
return View::make('admin/customers/show')->withCustomer($customer);
See also this question.
Upvotes: 0