Bensen
Bensen

Reputation: 149

Laravel return FALSE if field is NOT NULL (eloquent, whereNotNull)

I try to make the following blade statement work. If a Character is in a Team, display their name:

// ranking.blade.php
@if ($character->user->hasTeam()) [{{ $character->user->team->name }}] @endif

Problem
My solution always returns true, because the query will be executed:

// User.php
public function hasTeam()
{
    return ($this->whereNotNull('team_id')->first()) ? true : false ;
}

SQL

// dd($this->whereNotNull('team_id')->toSql());
-> "select * from `users` where `team_id` is not null"

Questions

Upvotes: 1

Views: 2646

Answers (3)

xar
xar

Reputation: 1439

An alternative to @Jerodev 's answer, you can also make use of accessors :

public function getHasTeamAttribute()
{
    return isset($this->team_id);
}

so whenever you need to access the property you can just call

$user->has_team

Upvotes: 2

Michal
Michal

Reputation: 5220

What does $this->whereNotNull('team_id')->first() return?

Keep in mind that your ternary operator listens to truthy values.

My guess is that you get always true because the query is actuall always getting executed. You would get false only if there was an error connecting to database.

Upvotes: 0

Jerodev
Jerodev

Reputation: 33186

You can just check if the team_id field of a user is null. This way, no extra queries are required.

public function hasTeam()
{
    return isset($this->team_id);
}

Upvotes: 2

Related Questions