Tuesday, March 21, 2017

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></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)



via Andrea Nobili

Advertisement