AbehoM's avatar

Redirect back with error not setting the key

I was wondering, how can I set the error message and the key so I can get in the blade using @error directive? I'm trying this way: return redirect()->back()->withErrors(['insufficient' => 'You do not have enough coins to proceed']); but it's not seeting the insufficient only the message error.

0 likes
8 replies
leandromatos's avatar

Try

return Redirect::back()->withErrors(['insufficient' => 'You do not have enough coins to proceed']);
@if($errors->any())
    {{$errors->first()}}
@endif
AbehoM's avatar

@LEANDROMATOS - I was actually wondering if it could be possible to set the keys, this way I could get different errors based on its key like using @error('insufficient'). I don't know how the Laravel validation does internally for this to work.

AbehoM's avatar

@LEANDROMATOS - It shows only the values: array(1) { [0]=> string(39) "You do not have enough coins to proceed" } for {{ var_dump($errors->all()) }}, I can't use dd otherwise it won't even show the form so I can press the button haha.

leandromatos's avatar
Level 34

@zfdeveloper Hey man, i tried here and error directive works without problem. When i submit the form, the store method on controller returns the expected message!

In my routes file

Route::get('/', 'SomeController@index');
Route::post('/store', 'SomeController@store');

In my SomeController

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Redirect;

class SomeController extends Controller
{
    public function index()
    {
        return view('index');
    }

    public function store()
    {
        return Redirect::back()->withErrors(['insufficient' => 'You do not have enough coins to proceed']);
    }
}

In my index view

<form method="POST" action="/store">
        @csrf

        @error('insufficient')
            {{ $message }}
        @enderror

        <input type="submit" value="Submit">
 </form>
AbehoM's avatar

@LEANDROMATOS - What the heck, it does work, for some reason it wasn't working before. REALLY weird. Thank you for your time. ♥

1 like

Please or to participate in this conversation.