Displaying the Error Messages in Laravel after being Redirected from controller
In Laravel, you can use the withErrors method to pass error messages to a view after a redirect.
In Laravel, you can use the withErrors method to pass error messages to a view after a redirect.
Here's an example of how you can use it in a controller:
Use the withErrors method to pass error messages to a view after a redirect in Laravel
<?php
public function store(Request $request)
{
$validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator);
}
$post = new Post;
$post->title = $request->title;
$post->body = $request->body;
$post->save();
return redirect('posts')->with('success', 'Post has been added');
}
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
To display the error messages in the view, you can use the $errors variable. This variable will be available in the view and will contain the error messages:
Display error messages in the view using the $errors variable
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endifYou can also use the @error directive to display an error message for a specific field:
Use the @error directive to display a specific field error
@error('title')
<div class="alert alert-danger">{{ $message }}</div>
@enderror