0

I am very new to the laravel, I am writing a normal if condition I want to convert that if condition to ternary operator ,please help me to convert it

$posts=DB::table('posts')->where('name',$id)->exists();
if($posts == false)
return $user->hasRole() ||$user->hasRights();
Kamafeather
  • 7,050
  • 13
  • 52
  • 88
Code cracker
  • 254
  • 1
  • 11
  • Does this answer your question? [How to replace "if" statement with a ternary operator ( ? : )?](https://stackoverflow.com/questions/1506527/how-to-replace-if-statement-with-a-ternary-operator) – Peppermintology Oct 08 '21 at 18:03
  • 1
    Laravel is a PHP framework, so a Ternary is as documented: https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary, basically `$boolean ? $ifTrue : $ifFalse`. That being said, `if(!$posts){ ... } else { ... }` is perfectly fine here. – Tim Lewis Oct 08 '21 at 18:04

2 Answers2

1

I don't use Laravel but I think it's a PHP framework, so, as documented here:

return $posts == false ? $user->hasRole() ||$user->hasRights() : return_val_if_false

You said you don't want to specify a return value if false. In that case you can simply do:

return $posts == false && ($user->hasRole() ||$user->hasRights());

This doesn't use ternary operators though, there is no way to do what you specifically want I think.

Konrad
  • 802
  • 9
  • 29
1

The ternary operator is the same as Javascript with

[condition] ? [if true] : [if false]

if you want to refer to this is not Laravel, because Laravel is just a framework, you need to look for PHP because PHP is the language.

Jose Lora
  • 1,430
  • 3
  • 10
  • 17