Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 : How to use findOrFail() method?

Tags:

php

laravel-5

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://my.url/users/10/edit 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

like image 710
Dark Cyber Avatar asked Sep 23 '15 11:09

Dark Cyber


Video Answer


2 Answers

This does what you asked. No need for exceptions.

public function edit($id)
{
    $data = User::find($id);
    if ($data == null) {
        // User not found, show 404 or whatever you want to do
        // example:
        return View('admin.user.notFound', [], 404);
    } else {
        $roles = Role::where('title', '!=', 'Super Admin')->get();
        return View('admin.user.edit', compact(['data', 'roles']));
    }
}

Your exception handler is not necessary as it is. Regarding Illuminate\Database\Eloquent\ModelNotFoundException:

If the exception is not caught, a 404 HTTP response is automatically sent back to the user, so it is not necessary to write explicit checks to return 404 responses when using [findOrFail()].

Also, I'm pretty sure you get the exception page instead of 404 now because you're in debug mode.

like image 118
bernie Avatar answered Oct 13 '22 01:10

bernie


public function singleUser($id)
{
    try {
        $user= User::FindOrFail($id);
        return response()->json(['user'=>user], 200);
    } catch (\Exception $e) {
        return response()->json(['message'=>'user not found!'], 404);
    }
}
like image 42
Iklan Hits Avatar answered Oct 13 '22 00:10

Iklan Hits