Saturday, April 15, 2017

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()) [] @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

  • Is the whereNotNull method useless in this instance?
  • How do I only display a team's name if the User is member of a Team?


via Bensen

Advertisement