0

I have a route to show my users' profile in my laravel project. But when you go to an url and fill in a username that does not exist it gives a nasty error, obviously because that username doesn't exist in the database.

Has anyone any idea how I can error handle this?

Here's my route:

Route::get('user/{name}', 'userController@showUser');

Here's my function:

public function showUser($name)
    {
        $user = User::where('name' , '=', $name)->firstOrFail();
        return view('user.show', compact('user'));
    }

This is what I've tried but doesn't seem to work since I get this error: View not found

$user = User::where('name' , '=', $name)->first();
        if(!empty($user)){
            return view('user.show', compact('user','projects'));
        }else{
            return view('user');
        }
Cruzito
  • 338
  • 3
  • 7
  • 18
  • don't use `firstOrFail`, but `first`, check if you found something yourself and react by redirecting or whatever you want to do. – Pevara Jun 18 '16 at 11:42
  • @Pevara That's the issue I have, I don't know exactly how to redirect when there are no results. I am failry new to laravel :) – Cruzito Jun 18 '16 at 11:46
  • https://laravel.com/docs/5.0/responses#redirects – Pevara Jun 18 '16 at 11:48

2 Answers2

1

you can use first method to get username from user table

public function showUser($name){
        $user = User::where('name' , '=', $name)->first();
        if(!empty($user)){
          return view('user.show', compact('user'));
       }

}

}

Lets make sure your view file is in user folder

Mehul Kuriya
  • 608
  • 5
  • 18
1

Try this

        $user = User::where('name' , '=', $name)->first();
        if(!empty($user)){
            return view('user.show', compact('user','projects'));
        }else{
            return redirect()->route('/routeWhereYouWannaSend');
        }

For more info read HTTP Responses

2nd Solution: If you want to redirect to Homepage on route(s) that doesn't exist at all Link

Community
  • 1
  • 1
Iftikhar uddin
  • 3,117
  • 3
  • 29
  • 48