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

时间:2018-01-27 08:50:11

标签: php laravel laravel-5 blade

我有一系列产品,我试图找到每种产品的最低价格。

首先,我要尝试从Controller成功调用函数并传递产品的 <span class="text-bold"> @php use App\Http\Controllers\ServiceProvider; echo ServiceProvider::getLowestPrice($product_cat->id); @endphp </span> 并将其打印出来。

blade.php

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

知道为什么llvm/lib/Support/Unix/Signals.inc无法在这里工作?

5 个答案:

答案 0 :(得分:5)

您无法在方法

中使用use关键字

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

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

答案 1 :(得分:5)

答案 2 :(得分: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)}}

答案 3 :(得分: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);;
    }

我希望这会对您有所帮助。

答案 4 :(得分:0)

它甚至更容易,您可以像这样直接调用它:

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