The error "Call to a member function hasRole() on null" suggests that the $request->user() is returning null, meaning that there is no authenticated user.
To fix this issue, you need to ensure that the user is authenticated before calling the hasRole() method. You can do this by adding a middleware to your route or controller that handles the share() method.
Here's an example of how you can modify your code to handle this issue:
public function share(Request $request): array
{
// Check if the user is authenticated
if ($request->user()) {
return array_merge(parent::share($request), [
'is_admin' => $request->user()->hasRole('admin')
]);
}
// If the user is not authenticated, return an empty array
return [];
}
By adding the if ($request->user()) condition, you ensure that the hasRole() method is only called if there is an authenticated user. If there is no authenticated user, the method will return an empty array.
Remember to also make sure that you have properly set up authentication in your Laravel application, including configuring the authentication middleware and routes.