Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel 5.2刀片中使用变量的正确方法_Php_Templates_Variables_Blade_Laravel 5.2 - Fatal编程技术网

Php Laravel 5.2刀片中使用变量的正确方法

Php Laravel 5.2刀片中使用变量的正确方法,php,templates,variables,blade,laravel-5.2,Php,Templates,Variables,Blade,Laravel 5.2,因此,我知道如何通过控制器传递变量,例如,如果它是一个查询数组,我将这样做 public function index() { $query = Request::get('q'); if ($query) { $users = User::where('username', 'LIKE', "%$query%")->get(); } return view('view', compact('users')); } 当我在刀刃上时,我会做

因此,我知道如何通过控制器传递变量,例如,如果它是一个查询数组,我将这样做

public function index()
{
    $query = Request::get('q');
    if ($query) {
        $users = User::where('username', 'LIKE', "%$query%")->get();
    }

    return view('view', compact('users'));
}
当我在刀刃上时,我会做的

 @if( ! empty($users))     
    @foreach($users as $user)
        {{ $user->username }}
    @endforeach
 @endif
现在我的问题是如何使用foreach中的变量设置变量?目前,我正在刀片模板文件中使用PHP,但我觉得这很混乱,以下是我所拥有的

@if( ! empty($users))     
    @foreach($users as $user)
     <?php 
        $lastOnline = \Carbon\Carbon::createFromTimeStamp(strtotime($user->last_online))->diffForHumans();
        $fiveMinsAgo = \Carbon\Carbon::now()->subMinute(5);
     ?>
        {{ $user->username }}
        @if ($user->last_online <= $fiveMinsAgo)
            {{ $lastOnline }}
        @else 
            Online Now
        @endif
    @endforeach
@endif
@if(!empty($users))
@foreach($users作为$user)
{{$user->username}

@如果($user->last_online找到了我的问题的解决方案,如果有人在寻找它

public function getLastOnlineAttribute($value)
{
    $fiveMinsAgo = \Carbon\Carbon::now()->subMinute(5);
    $thirtMinsAgo = \Carbon\Carbon::now()->subMinute(30);
    $lastOnline = \Carbon\Carbon::createFromTimeStamp(strtotime($value))->diffForHumans();
    if ($value <= $fiveMinsAgo) {
        echo 'Last Active: '.$lastOnline.'';
    }
    else {
        echo 'Online Now';
    }

}
公共函数getLastOnlineAttribute($value)
{
$fiveMinsAgo=\Carbon\Carbon::now()->亚微米(5);
$thirtMinsAgo=\Carbon\Carbon::now()->subMinute(30);
$lastOnline=\Carbon\Carbon::createFromTimeStamp(strtotime($value))->diffForHumans();
如果($value last_online,它将进入用户模型),如果你想了解更多信息,它被称为雄辩的变种人

它获取变量的数据,例如{{$user->last_online}


请注意,下划线在函数名中被转换为CamelCase,输出设置为$value,然后您可以在函数内部设置变量,并根据自己的意愿对输出进行建模,然后在blade中您可以摆脱所有多余的垃圾,只需使用{{{{$user->last_online}

这是您想要的,谢谢,所以我的意思是,有没有办法从控制器或视图而不是刀片设置这些?从您链接的内容来看,我只是调出了刀片,没有任何办法。因此,我认为这是最好的选择。我个人认为,注释样式变量声明比使用普通命令更混乱到目前为止,后者是我解决它的方法。