I have ACL set up with laravel. I have the following helper:
function user($user_id = null)
{
if (!$user_id) return Auth::user();
return User::where('id', $user_id)->first();
}
I have this helper function so I don't have to type the long Auth::user()
.
Here's the problem. I have ACL set up so when I do something like the following in my model and the user is not logged in, I get an error.
if (user()->can('edit-blog')) {
echo 'you can edit blog!';
}
This is the error if the user is not logged in:
Call to a member function can() on null
Now, I have the following code everywhere in my site. I am using ACL in almost every view and model and controller. I don't want to have to do something like the following just to not get the error.
if (user() && user()->can('edit-blog')) {
// do stuff
}
How can I return false if there is a "null" error or an exception?
** What I have tried **
I have tried try/catch
but it does not do anything:
try {
if (!$user_id) return Auth::user();
return User::where('id', $user_id)->first();
} catch (Exception $ex) {
return false;
}
Thank you for your support.
You need to check if the user is logged in before calling can
if(Auth::check() && user()->can('edit-post')){
Return true;
}else{
Return false;
}