Hi, you probably have relations on your models, if so
public function show()
{
return view ('user.profile.show', ['team' => Auth::user()->team]);
}
if user has team, good, if not - then null will be returned
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Good afternoon all,
Quick info about situation :
User registers -> User logs in
The next step that I want to do is get the user to finish his profile so
User hits /profile
This page contains a tab : User profile and a tab Team profile
All worked until the point I added the Team profile.
Controller looks like this :
public function show(){
$team = Team::where('id', Auth::User()->team_id)->firstOrFail();
return view ('user.profile.show', ['team'=>$team]);
}
As you (probably) can imagine (but I ofc didn't think of that) the User did not create or joined a team yet. So the 'firstOrFail' method does it's thing and returns a 404.
So my question is :
Is my approach wrong by using the firstOrFail() method ?
Or, I tried the following conditional (but failed):
public function show(){
try{
$team = Team::where('id', Auth::User()->team_id)->firstOrFail();
// Team exists
return view ('user.profile.show', ['team'=>$team]);
} catch (ErrorException $e) {
// Team does not exist
return view('user.profile.show');
}
It still gets stuck on the fail...
Than I tried this conditional :
public function show(){
$team = Team::where('id', Auth::User()->team_id)->get();
//Found
return view ('user.profile.show', ['team'=>$team]);
if($team->isEmpty()){
return view ('user.profile.show');
}
}
This conditionals throws up = does not exist on this collection instance
So before I try to dig into that issue, is this last approach the best I can do in this case?
Hi @mirlan bekturov,
In addition to the comment of Sergiu, your remark solves this. However, in my situation the condition needs to be met on the controller.
I've updated my UserController like this :
public function show(){
if(!empty(Auth::User()->team_id)){
$team = Team::where('id', Auth::User()->team_id)->firstOrFail();
return view ('user.profile.show', ['team'=>$team]);
}
return view('user.profile.setup');
}
So first in my show-method I need to check if the team_id field is empty or not (could have used isset also) When this field is not empty (a team has been linked) the first route will be hit.
If the field is empty the second route will be hit, which is similar, except instead of returning a view that contains $team fields, it will return a view only consisting of $user-fields and under the Team tab an option to add a team.
Your suggestion did help me realise a simple solution, still not 100% this is the best approach though.
Please or to participate in this conversation.