如何在视图中访问Laravel类?

时间:2016-12-16 13:22:09

标签: php laravel laravel-5

如果我在控制器,这一行就可以了。

use App\UBBUserSetting, App\UBBSetting;

但我在视图中

我正在尝试在我的视图中包含我的课程( .blade.php

我不能

    use App\UBBUserSetting, App\UBBSetting;


    $ubb_user_settings = UBBUserSetting::where('cpe_mac','=',$cpe_mac)->get();
    $ubb_settings = UBBSetting::where('cpe_mac','=',$cpe_mac)->first();
    if($ubb_settings != null){
        $jump_bandwidth = $ubb_settings->jump_bandwidth;
        $paid = $ubb_settings->price_per_jump;
    }

    $option2 = 0;

    if($ubb_user_settings != null){
        $option1_selected = [];
        $option2_selected = [];

        $lines = count($ubb_user_settings);

        foreach ($ubb_user_settings as $i => $ubb_user_setting) {
            if($ubb_user_setting->option == 1){
                $option1_selected[$i]['d'] = $ubb_user_setting->created_at->format('d');
                $option1_selected[$i]['threshold'] = (int)$ubb_user_setting->volume_current_limit;

            }else{

                $option2++;
                $option2_selected[$i]['d'] = $ubb_user_setting->created_at->format('d');
                $option2_selected[$i]['threshold'] = (int)$ubb_user_setting->volume_current_limit;
                $option2_selected[$i]['next_threshold'] = $threshold + ($jump_bandwidth * $option2);

            }
        }

    }

错误

enter image description here

怎么会这样做呢?

任何提示?

4 个答案:

答案 0 :(得分:4)

如果您尝试在Blade视图中使用任何PHP代码,请使用<?php ?>标记并使用完整命名空间:

<?php
    ....
    $ubb_user_settings = \App\UBBUserSetting::where('cpe_mac','=',$cpe_mac)->get();
    ....
?>

但是从视图运行查询是一种可怕的做法。你应该学习MVC模式。

答案 1 :(得分:3)

这应该是你的代码:

$ubb_user_settings = \App\UBBUserSetting::where('cpe_mac','=',$cpe_mac)->get();
$ubb_settings = \App\UBBSetting::where('cpe_mac','=',$cpe_mac)->first();
if($ubb_settings != null){
    $jump_bandwidth = $ubb_settings->jump_bandwidth;
    $paid = $ubb_settings->price_per_jump;
}

$option2 = 0;

if($ubb_user_settings != null){
    $option1_selected = [];
    $option2_selected = [];

    $lines = count($ubb_user_settings);

    foreach ($ubb_user_settings as $i => $ubb_user_setting) {
        if($ubb_user_setting->option == 1){
            $option1_selected[$i]['d'] = $ubb_user_setting->created_at->format('d');
            $option1_selected[$i]['threshold'] = (int)$ubb_user_setting->volume_current_limit;

        }else{

            $option2++;
            $option2_selected[$i]['d'] = $ubb_user_setting->created_at->format('d');
            $option2_selected[$i]['threshold'] = (int)$ubb_user_setting->volume_current_limit;
            $option2_selected[$i]['next_threshold'] = $threshold + ($jump_bandwidth * $option2);

        }
    }

}

您可以在课前设置命名空间,因此在App\UBBUserSetting之前它将是::where()。因为您在刀片视图中而不是在类中,所以您应该在类之前使用命名空间。

希望这有效!

答案 2 :(得分:3)

分开:

use App\UBBUserSetting;
use App\UBBSetting;

答案 3 :(得分:0)

这样写

@php
use App\UBBUserSetting;
use App\UBBSetting;
@endphp