LAravel作曲家查看依赖关系并没有看到

时间:2017-08-17 09:24:44

标签: php laravel dependency-injection

我有这样的错误:

Unresolvable dependency resolving [Parameter #0 [ <required> $products ]] in class App\Http\ViewComposers\ShoppingCartComposer

我想将我的数据从CartController发送到ViewComposer(这里是$ products),但我的依赖关系并没有看到它。

我的代码是: 查看作曲家:

namespace App\Http\ViewComposers;

 use Illuminate\View\View;

class ShoppingCartComposer
{

protected $products;


public function __construct(Array $products)
{
    // Dependencies automatically resolved by service container...
    $this->products = $products;
}

public function countProducts(){

}

public function compose(View $view)
{
    $view->with('count', 'test');
}
}

这是Composer服务提供商:

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{

public function boot()
{

    View::composer(
        'shopping-cart', 'App\Http\ViewComposers\ShoppingCartComposer'
    );

}

public function register()
{

}

}

这里是购物车Conrtoller,我希望从索引控制器发送和产品:

class CartController extends Controller
{
public function index()
{
    if (Session::has('shoppingCart')) {
        $products = Session::get('shoppingCart');
    } else {
        $products = [];
    }

    return view('shopping-cart', ['products' => $products]);
}

1 个答案:

答案 0 :(得分:0)

它找不到变量$products,因为你需要将它传递给视图编辑器中的compose方法:

public function compose(View $view)
{
    $view->with([
        "products" => $this->products,
        "test" => "TEST"
    ]);
}

希望这会对你有所帮助。