laravel blade 中带有 {{ }} 的条件运算符的语法

syntax for conditional operator with {{ }} in laravel blade

我正在尝试对从控制器返回的值实施条件运算符以创建一些自定义视图。

front.blade

@if({{count($users)}} <= 5) <!-- if total number of rows in users table is less than or equal to 5 -->
          <h3> total number of rows less than or equal to 5 </h3> 
@endif

控制器

$users = User::all();
return view('front', [ 'users'=>$users]);

错误是

语法错误,意外的“<”(查看:\resources\views\front.blade.php)

尝试了将条件放在 {{ }} 内或引用运算符或常量值 5 的所有排列组合,错误仍然相同。我是 laravel 的新手,这可能是 laravel 或 php 的根本错误。

只需删除 {{}},除了 Blade 指令(@if在本例中)

之外不需要它们

您需要删除 if 条件中的 {{ }}

像这样。

  @if(count($users) <= 5) <!-- if total number of rows in users table is less than or equal to 5 -->
     <h3> total number of rows less than or equal to 5 </h3> 
  @endif

在 Controller 中像这样更改您的代码 -

$users = User::all();
return view('front', compact('users'));

Blade文件代码-

@if(count($users) <= 5) <!-- if total number of rows in users table is less than or equal to 5 --><h3> total number of rows less than or equal to 5 </h3>@endif

首先你需要了解什么时候需要使用大括号。
当你在 blade 文件中显示数据时你需要使用大括号。喜欢

Hello, {{ $name }}.

您可以使用@if、@elseif、@else 和@endif 指令构造if 语句。这些指令与其 PHP 对应指令的功能相同:

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

你的解决方案

 @if(count($users) <= 5) <!-- if total number of rows in users table is less than or equal to 5 -->
     <h3> total number of rows less than or equal to 5 </h3> 
  @endif

有关详细信息,请参阅 laravel 文档 https://laravel.com/docs/7.x/blade#if-statements