Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1 Creating default object from empty value

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
like image 559
Kristin K Avatar asked Jun 30 '16 06:06

Kristin K


3 Answers

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">
like image 171
Ivanka Todorova Avatar answered Nov 03 '22 04:11

Ivanka Todorova


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">
like image 32
Hiren Makwana Avatar answered Nov 03 '22 03:11

Hiren Makwana


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 :)

like image 1
Samvedna Avatar answered Nov 03 '22 05:11

Samvedna