Blade @include help

Published 2 years ago by madsynn

Hi everyone, i was wondering if you guys might be able to help me understand the @include in blade.

I have a blade page i am trying to organize and break into smaller chunks of with the @include in a laravel 5.1 site and keep running into problems.

If i use this according to the laravel docs it should get all the same data available in the parent.

Even though the included view will inherit all data available in the parent view, you may also pass an array of extra data to the included view:

Problem is it is not working. If i use @inject('model', 'App\Model') some of the data seems to work but on other parts it does not.

I also have a header with a menu item that has to always be present and i cannot get that to keep it looping through the data because on some pages it tells me the variable is not valid and its an incorrect for each.

layout.blade.php
│   └── INCLUDES header.blade.php
│       └── INCLUDES menu-cart.blade.php  (this part needs to show the cart products  and is not working)
└── EXTENDS
    └── index.blade.php
        ├── INCLUDES product-details.blade.php
        ├── INCLUDES product-sidebar.blade.php
        ├── INCLUDES product-features.blade.php
        ├── INCLUDES product-options.blade.php
        └── INCLUDES product-additional.blade.php

The menu-cart.blade.php is the component i need to loop through the current user or guests car at all times.

All the includes inside the index.blade.php are wrapped in a foreach on the index.blade.php but when i try and get data back using something like this {!!$product->name !!} i get a invalid foreach loop variable products is not valid.

Please tell me what you think please.

wolle404

You can try to pass your Model as a variable like @include('my.view', ['model' => $model])

Otherwise you can try to do a @inject('...') in your partials.

Edit: You can also share your Model for all views. So you don't have to @inject it into the view

madsynn

@wolle404 Thanks,

Can you show me an example of share of view?

wolle404

Sure, take a look on this: https://laravel.com/docs/5.3/views#passing-data-to-views

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        View::share('key', 'value');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Please sign in or create an account to participate in this conversation.