I am using Laravel 5.1 PHP framework. When I try to update my record, I get the error:
"ErrorException in AdminController.php line 108: Creating default object from empty value".
I have searched in google but I can't find any results to solve my problem.
Routes
Route::get('/admin/no', 'AdminController@index');
Route::get('/admin/product/destroy/{id}', 'AdminController@destroy');
Route::get('/admin/new', 'AdminController@newProduct');
Route::post('/admin/product/save', 'AdminController@add');
Route::get('/admin/{id}/edit', 'AdminController@edit');
Route::patch('/admin/product/update/{id}', 'AdminController@update')
AdminController
public function edit($id)
{
$product = Product::find($id);
return view('admin.edit', compact('product'));
}
public function update(Request $request, $id)
{
$product = Product::find($id);
$product->id = Request::input('id');
$product->name = Request::input('name');
$product->description = Request::input('description');
$product->price = Request::input('price');
$product->imageurl = Request::input('imageurl');
$product->save();
//return redirect('/admin/nο');
}
enter code here
edit.blade.php
div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Edit Product</div>
</div>
<div class="panel-body" >
<form action="/admin/product/update/{id}" method="POST"><input type="hidden" name="_method" value="PATCH"> <input type="hidden" name="_token" value="{{ csrf_token() }}">
enter code here
The problem is that $product = Product::find($id);
returns NULL
. Add the check:
if(!is_null($product) {
//redirect or show an error message
}
Though this is your update method, so probably you're having an error while building the url for this method. It might be a wrong id you're passing to this route.
Your form action
has an error:
<form action="/admin/product/update/{id}" method="POST">
Notice the curly braces, Blade's syntax is {{ expression }}
, not just {}
. So id
is never passed to the product.update
route. Just change it to:
<form action="/admin/product/update/{{$id}}" method="POST">
For update entity in laravel uses PUT method not POST. update form method and try.
<form action="/admin/product/update/{id}">
<input name="_method" type="hidden" value="PUT">
check if the product exists then do the update The form will look like this
<form action="/admin/product/update/{{$id}}" method="POST">
$ sign was missing :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With