Laravel 5.5从带有参数的刀片视图调用控制器功能

问题描述 投票:4回答:5

我有一个滑块的产品,我试图找到每个产品的最低价格。

所以我首先尝试从Controller成功调用函数并传递产品的id并将其打印出来。

blade.php

 <span class="text-bold">
   @php
    use App\Http\Controllers\ServiceProvider;
    echo ServiceProvider::getLowestPrice($product_cat->id);
   @endphp
 </span>

路线

Route::post('/getLowestPrice/{id}', 'ServiceProvider@getLowestPrice');

调节器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ServiceProvider extends Controller
{
    public static function getLowestPrice($id) {
        return $id;
    }
}

我收到一个错误

Parse error: syntax error, unexpected 'use' (T_USE) 

知道为什么use不在这里工作?

php laravel laravel-5 blade
5个回答
8
投票

你不能在方法中使用use关键字

你可以编写完整的类路径,就像这样

 <span class="text-bold">
   @php
    echo App\Http\Controllers\ServiceProvider::getLowestPrice($product_cat->id);
   @endphp
 </span>

10
投票

@Ali显然是正确的,我建议你接受他的回答。

不过,我想补充说,还有一个服务注入指令,它是为了这个目的而构建的,并且使用起来更加清晰。

@inject('provider', 'App\Http\Controllers\ServiceProvider')

<span class="text-bold">
    {{ $provider::getLowestPrice($product_cat->id) }}
</span>

文件:https://laravel.com/docs/5.5/blade#service-injection


1
投票
//Create a static type function in your controller.The function must be a static type function.

    <?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;

    class ServiceProvider extends Controller
    { 
        public static function getLowestPrice($val){
            // do your stuff or return something.
        }
    }

    //Then Call the ServiceProvider Controller function from view


    //include the controller class.
    <?php use App\Http\Controllers\ServiceProvider;?>
    //call the controller function in php way with passing args.
    <?php echo ServiceProvider::getLowestPrice($product_cat->id); ?>
    // Or call the controller function in blade way.
    {{ServiceProvider::getLowestPrice($product_cat->id)}}

1
投票

它可以更容易,您可以直接调用它:

<span class="text-bold">
    {{App\ServiceProvider::getLowestPrice($product_cat->id)}}
</span>

0
投票

从视图调用控制器功能的一个简单概念是:例如,你有一个按钮在视图中href =“你的URL”

 <a href="/user/projects/{id}" class="btn btn-primary">Button</a>

现在在web.php中定义一个路由:

Route::get('/user/projects/{id}', 'user_controller@showProject');

各控制器中的功能如下所示:

 public function showProject($id){
 $post =posts::find($id);
 return view('user.show_projects')->with('post', $post);;
    }

我希望这能帮到您。

© www.soinside.com 2019 - 2024. All rights reserved.