Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.5 call Controller function from blade view with parameter

I have a slider of products and i'm trying to find the lowest price of each product.

So i'm trying, first of all, to successfully call a function from a Controller and pass the id of the product and also print it out.

blade.php

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

Route

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

Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

And I get an error

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

Any idea why use is not working here?

like image 490
Konstantinos Natsios Avatar asked Jan 27 '18 08:01

Konstantinos Natsios


1 Answers

@Ali is obviously correct, and I suggest you accept his answer.

I'd like to add, though, that there's a service injection directive as well which was built for this exact purpose, and which is a little cleaner to use.

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

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

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

like image 128
Joel Hinz Avatar answered Dec 05 '22 10:12

Joel Hinz