David David - 3 months ago 28
PHP Question

Check if there is a 404 response error in controller- Laravel 5

I working on the Halo 5 API, and users can register with their gamer-tags. When they do, they can log in, and when they login, they can go to their profile to look up their stats for Halo 5. But obviously some users wont enter legit gamertags. And thats were I need some validation in my controller that returns the view for the profile.

Here is a simple example of the controller:

public function index ($slug) {

// Emblem URL.
$getPlayerEmblemImage = app('App\Http\Controllers\Api\GetGeneralStatsController')->getPlayerEmblemImage($slug);

// Get General Player Arena Stats
$playerGeneralStats = app('App\Http\Controllers\Api\GetGeneralStatsController')->getPlayerArenaStats($slug);
$playerGeneralStatsArray = $this->getPlayerGeneralStatsArray($playerGeneralStats);

// Get the Spartan Rank and XP
$spartanRank = json_decode($playerGeneralStatsArray['SpartanRank'], true);
$XP = json_decode($playerGeneralStatsArray['Xp'], true);
$Gamer_Tag = json_encode($playerGeneralStatsArray['Gamer_Tag'], true);

$user = User::whereSlug($slug)->firstOrFail();

return view('profile.index',
compact(
'user',
'spartanRank',
'XP',
'getPlayerEmblemImage',
'Gamer_Tag',
)
);
}


My problem is, if a user does not exist, it throws this error:


ClientException in RequestException.php line 107:
Client error:
GET https://www.haloapi.com/profile/h5/profiles/some%20useer/spartan
resulted in a
404 Not Found
response:


How can I do some checking, and return different results, if that player is not found?

Maybe something like this?

public function index ($slug) {

if (// Doesnt exist, show this) {
// do some other code here
return view('profile.index', compact('user'))

} else {

// Code here....

return view('profile.index',
compact(
'user',
'spartanRank',
))
}

}

Answer

I think you can use exception handling here.

try{
    // Code here....

 return view('profile.index',
            compact(
                'user',
                'spartanRank',
            ))
}
} catch(ClientException $exception) {
{
    // do some other code here
    return view('profile.index', compact('user'))
}

Import use GuzzleHttp\Exception\ClientException; in your controller

use GuzzleHttp\Exception\ClientException;