How to print laravel withError messages on blade file. How to send custom message withError() method. Laravel redirect back with errors not working. How to send error messages with redirect back in laravel 7, laravel 8, laravel 9.
Laravel send error messages with redirect method
Laravel provide withError() method for sending errors to blade file. withError function take single message or array of error messages see below example
UserController.phpclass UserController extends Controller{ public function login(Request $request){ $validator = Validator::make($request->all(), [ 'email' => 'required', 'password' => 'required', ]); if($validator->fails()) return back()->withErrors($validator); try { if(auth()->attempt(['email' => $request->email, 'password' => $request->password])) return "login success"; else return back()->withErrors('These credentials do not match our records.'); } catch (\Exception $e) { return back()->withErrors(["custom_name" => "Either something went wrong or invalid access!"]); } } }
How to print laravel withError() messages
In the laravel blade file, we print error messages of different types. In the example first case we print errors by running foreach loop it prints all error return by withError function and in second case print error by its key name.
View file login_form.blade.php// print all type of error messages which return withErrors() method @if(count($errors) > 0) @foreach ($errors->all() as $error) <p>{{ $error }}</p> @endforeach @endif //print error message by key name @error('custom_name') <p>{{$message}}</p> @enderror