Search code examples
phplaravellaravel-5laravel-5.4laravel-validation

How can manually return an error page with a specific message into the $errors from a Controller method in a Laravel application?


I am pretty new in PHP and moreover in Laravel. I am working on a Laravel 5.4 project and I have the following problem.

I have this custom error page named error.blade.php:

@extends('layouts.app')

@section('content')

    <h1 class="page-header"><i class="fa fa-exclamation-triangle" aria-hidden="true" style="margin-right: 2%"></i>Riscontrati errori</h1>

    @if (count($errors) > 0)
        <div class="alert alert-danger">
            <strong>Whoops!</strong> Sono stati riscontrati errori nel tuo input.<br /><br />
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif


@endsection

As you can see this class show the error messages into the $errors variable? (it came from validation rules retrieved error, so what exactly is it? An array? or what?)

Then into a controller class I have this controller method:

public function activate(ActivateRequest $request) {

    $email = $request->input('email');
    $token = $request->input('token');

    $results = DB::select('select * from pm_user where email = :email', ['email' => $email]);

    $tokenFromDB = $results[0]->token;

    if($token != $tokenFromDB) {
        // PUT AN ERROR INTO THE $errors ARRAY
        // RETURN THE error.blade.php VIEW
    }

    return 'Works!';
    // do stuff
}

So, as you can see in the previous code snippet, I have this case:

if($token != $tokenFromDB) {
    // PUT AN ERROR INTO THE $errors ARRAY
    // RETURN THE error.blade.php VIEW
}

So in this specific case I want to add a textual error message into the $errors and return the error.blade.php showing this error message.

How can I do it manually? (I am not using a validation rule in this case, I have to do it by code)


Solution

  • Use withErrors when building your view:

    return redirect('yourErrorBladeView')
       ->withErrors(['yourErrorName'=>'yourErrorDescription']);
    

    Or without a redirect:

    return View::make('yourErrorBladeView')
        ->withErrors(['yourErrorName'=>'yourErrorDescription']);
    

    From the Laravel Validation Errors documentation (https://laravel.com/docs/5.4/validation#quick-displaying-the-validation-errors):

    The $errors variable is bound to the view by the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used.