我有一个滑块的产品,我试图找到每个产品的最低价格。
所以我首先尝试从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
关键字
你可以编写完整的类路径,就像这样
<span class="text-bold">
@php
echo App\Http\Controllers\ServiceProvider::getLowestPrice($product_cat->id);
@endphp
</span>
@Ali显然是正确的,我建议你接受他的回答。
不过,我想补充说,还有一个服务注入指令,它是为了这个目的而构建的,并且使用起来更加清晰。
@inject('provider', 'App\Http\Controllers\ServiceProvider')
<span class="text-bold">
{{ $provider::getLowestPrice($product_cat->id) }}
</span>
//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)}}
它可以更容易,您可以直接调用它:
<span class="text-bold">
{{App\ServiceProvider::getLowestPrice($product_cat->id)}}
</span>
从视图调用控制器功能的一个简单概念是:例如,你有一个按钮在视图中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);;
}
我希望这能帮到您。