PinPiguin
PinPiguin

Reputation: 477

How to redirect in Laravel form on Post request?

I am new to Laravel and have run into following issue:

I have a form that should redirect on Post request but redirect does not happen.

This is my form:

<form action="{{route('cart-store')}}" method="post">
    {{csrf_field()}}
    <input type="hidden" name="id" value="{{$product->id}}">
    <input type="hidden" name="name" value="{{$product->name}}">
    <input type="hidden" name="price" value="{{$product->price}}">

    <button type="submit" class="btn btn-primary shop-button">Add to Card</button>
</form>

This is CartController:

public function store(Request $request)
{

    Cart::add($request->id, $request->name, 1, $request->price)->associate('App\Product');

    return redirect()->route('cart-index')->with('success_message', 'Item was added to your cart!');

}

And this is the route:

Route::post('/cart', 'CartContrloller@store')->name('cart-store');

When I click on submit button, the URL gets filled with product data but I reamain on the same page instead of being regirected to Cart.

I have no clue why this is happenning. Is threre a way to at least find out what is broken? I am on 5.7 version.

Upvotes: 4

Views: 13085

Answers (3)

I guess the best practice here could be using laravel's redirect back :

return redirect()->back()->with('success_message','any message you want')

you can not redirect to a post method, post routes except: csrf_token and some data with POST method, redirect it self is HTTP GET.

Upvotes: 3

Farid shahidi
Farid shahidi

Reputation: 352

You need to write this codes in your project:

Route::get('/cart', 'CartContrloller@index')->name('cart-index');
Route::post('/cart', 'CartContrloller@store')->name('cart-store');

public function index()
{
    return view('card.form');
}

public function store(Request $request)
{
    dd($request->all());
    Cart::add($request->id, $request->name, 1, $request->price)->associate('App\Product');

    return redirect()->route('cart-index');
}

check this out and if you are seeding form parameters again in your url I am sure that your blade form method is not post, its get, maybe your changes doesnt saved!

Upvotes: 0

Mohammad Hosseini
Mohammad Hosseini

Reputation: 1797

In your Controller you need to use route('cart-index') in redirect()

public function store(Request $request)
{

    Cart::add($request->id, $request->name, 1, $request->price)->associate('App\Product');

    return redirect(route('cart-index'))->with('success_message', 'Item was added to your cart!');

}

or if you need to redirect back try:

return redirect()->back()->with('success_message', 'Item was added to your cart!');

Upvotes: 0

Related Questions