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.

Here's an example of how you can use it in a controller:

<?php

public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    $post = new Post;
    $post->title = $validatedData['title'];
    $post->body = $validatedData['body'];
    $post->save();

    return redirect('posts')->with('success', 'Post has been added');
}

Watch a course Learn object oriented PHP

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:

@if ($errors->any())
<div class="alert alert-danger">
  <ul>
    @foreach ($errors->all() as $error)
    <li>{{ $error }}</li>
    @endforeach
  </ul>
</div>
@endif

You can also use the @error directive to display an error message for a specific field:

@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror