xhulio
xhulio

Reputation: 1103

data in included views in laravel

In my laravel app, I am passing a variable $data to a view which I will later include in another view. So in my controller method, I have:

public function random($id){
    $data = DB::table('reports')->where('id',$id);
    return view('partials.data', compact('data'));
}

In the partials.data I have:

{!! Form::open(['url'=>'reports/data',$id]) !!}

    <table class="table table-responsive table-condensed table-bordered tab-content">
        <thead>
            <tr>
                <th>Month</th>
                <th>Value</th>
            </tr>
        </thead>
        <tbody>
            @foreach($data as $dat)
                <tr>{{$dat->month}}</tr>
                <tr>{{$dat->value}}</tr>
            @endforeach
        </tbody>
    </table>

{!! Form::close() !!}

And in the main view I have this function:

function kpi_values(d) {
    // `d` is the original data object for the row
    kpi = d.id;
    return '@include("reports.data", array("id" => "kpi"))';
}

Which is triggered by:

$('#monthly_table tbody').on('click', 'td.details-controls', function () {
        var tr = $(this).closest('tr');
        var row = table.row(tr);
        if (row.child.isShown()) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        }
        else {
            row.child(kpi_values(row.data())).show();
            tr.addClass('shown');


        }
    });

When I run this I get the following error:

ErrorException in 3534c4c98c65c2d5267bf7c54a960d41 line 13:
Undefined variable: data

I have passed the variable data in my partial view, however, it seems like it requires it in the primary view.

Is there any way of doing this without passing the variable to the primary view? I don't want to mix things because the partial view controller method requires a parameter, while the primary view has no parameters in it.

Upvotes: 5

Views: 682

Answers (2)

Phi Nguyen
Phi Nguyen

Reputation: 3056

Laravel offers a great tool to handle this situation in which we need to pass some parameters to partial views without passing through the primary view. That is view composer. Here is an example :

In \App\Providers\AppServiceProvider.php file

public function boot()
{

    //get data and pass it to partials.data whenever partials.data is executed

 view()->composer('partials.data',function($view){
   $view->with('data',DataSet::all());
 });  

}

For more advanced, you can learn it from Laracast

Upvotes: 3

Pratik Soni
Pratik Soni

Reputation: 2588

You may use share methods to pass the data to all views.

return view('partials.data')->share('data', $data);

Upvotes: 0

Related Questions