mercredi 23 septembre 2015

Laravel 5 : How to use findOrFail() method?

I just follow some tutorial and so far what I do is :

my App/Exceptions/Handler.php

<?php
...
use Illuminate\Database\Eloquent\ModelNotFoundException;
...
public function render($request, Exception $e)
{
    if ($e instanceof ModelNotFoundException){
        abort(404);
    }
        return parent::render($request, $e);
}

and my UsersController looks like this :

...
public function edit($id)
{
    $data = User::findOrFail($id);
    $roles = Role::where('title', '!=', 'Super Admin')->get();
    return View('admin.user.edit', compact(['data', 'roles']));
}
...

with the above code if I visit http://ift.tt/1MIuYqS I get NotFoundHttpException in Application.php line 901:, yes because there is no id 10 in my record, but with User::find($id); I get normal view without data, since no id 10 in my record.

What I want is show default 404 then redirect to somewhere or return something if record not found with User::findOrFail($id); ? How I can do that ?

Thanks, any help appreciated.

ps: .env APP_DEBUG = true



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire