Home > Blockchain >  Laravel 8 If Statement which is better
Laravel 8 If Statement which is better

Time:03-23

Want to know which solution is better in Laravel 8 I need to Display the name = company_name if it is not empty / OR =user_name if company_name is empty OR = first_name last_name OR email

my code

     public function getDisplayName($email = false)
 {
     $name = $this->name??"";

 if(!empty($this->business_name) ){
     $name  = $this->business_name;
 }
 elseif(!empty($this->user_name) ){
     $name  = $this->user_name;
 }
 elseif (!empty($this->first_name) or !empty($this->last_name)) {
     $name = implode(' ', [$this->first_name, $this->last_name]);
 }

 elseif(!trim($name) and $email) $name = $this->email;
 else (empty($name)){
     $name = ' ';
 }
 return $name;
 }

will be better to use it for all cases or ifelse as in my code? Thanks

CodePudding user response:

If you put a return statement in an if() condition, you can use simple if (...) { return ... } syntax:

public function getDisplayName($email = ' ') {
  if (!empty($this->business_name)) {
    return $this->business_name;
  }

  if (!empty($this->user_name)) {
    return $this->user_name;
  }

  return trim("{$this->first_name} {$this->last_name}") ?? $email;
}

With this code, business_name, then user_name, then a combination of first_name and last_name, then $email, then finally ' ' will be returned. There isn't much use to assigning $name here if you're just going to return it at the end of the function, and you can simply set the final default as $email = ' '; and you're good.

CodePudding user response:

You can use Null coalescing operator.

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null; otherwise it returns its second operand.

public function getDisplayName($email = false)
{
    return $this->business_name
        ?? $this->user_name
        ?? trim(implode(' ', [$this->first_name, $this->last_name]))
        ?? $this->email
        ?? ' ';
}

I leave you another document link that will be useful for you.

CodePudding user response:

blade

@if($itams->count() > 0)
@else
@endif

other

if($this->id == 1)
{
   return
} else {

}
  • Related