Laravel 5.5 使用参数从 blade 视图调用 Controller 函数

Laravel 5.5 call Controller function from blade view with parameter

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

所以我首先尝试从 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 在这里不起作用吗?

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

你可以写完整的 class 路径,像这样

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

@阿里显然是正确的,我建议你采纳他的回答。

不过,我想补充一点,还有一个服务注入指令,它正是为此目的而构建的,使用起来更简洁。

@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

//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)}}

一个简单的概念,从视图调用控制器函数是: 例如您在视图中有一个带有 href="Your URL"

的 Button
 <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);;
    }

希望对您有所帮助。

可以更简单,你可以这样直接调用:

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