Search code examples
eloquentsavelaravel-artisanlaravel-6

Laravel: return redirect after saving correctly throws SQLSTATE[23000]: Integrity constraint violation


I'm using Laravel 6.11 with MAMP and after saving correctly data form into my database table I got the following error.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null (SQL: insert into products (name, price, description, long_description, updated_at, created_at) values (?, ?, ?, ?, 2020-02-05 19:00:35, 2020-02-05 19:00:35)) http://localhost:8000/admin/products

Routes

Route::get('/admin/products', 'ProductController@index'); 
Route::get('/admin/products/create', 'ProductController@create');
Route::get('/admin/products', 'ProductController@store');

ProductController

public function create()
{
    return view('admin.products.create');
}

public function store(Request $request)
{
    $product = new Product();
    $product->name = $request->input('name');
    $product->price = $request->input('price');
    $product->description = $request->input('description');
    $product->long_description = $request->input('long_description');
    $product->save(); //IT WORKS!! ALL DATA SAVED!!

    return redirect('/admin/products');
}

Create.blade

<form method="put" action="{{ url('/admin/products') }}">
.
.

Any ideas on how can I fix it?


Solution

  • Is it because you have two the same routes declared. These are.

    Route::get('/admin/products', 'ProductController@index');
    Route::get('/admin/products', 'ProductController@store');
    

    Now, when this line executed redirect('/admin/products');, Laravel will not invoke the first route you defined which is Route::get('/admin/products', 'ProductController@index');

    rather invoke the last route you defined, the Route::get('/admin/products', 'ProductController@store');.

    After invoking your store method in product controller, the method expect a request which includes the name, price and etc..

    Since you just redirected only without passing any argument, now laravel will throw you an error like what you had presented above.

    To solve that, change your second route method for ProductController@store. Like this

    Route::post('/admin/products', 'ProductController@store');