Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Blade: pass array as parameter to yield section

i would like to pass an array as parameter from my controller to the blade template.

My controller looks like this:

$myArray = array('data' => 'data');
return View::make('myTableIndex')
    ->nest('myTable', 'my_table_template', $myArray)

In my blade template i've got a yield like this:

@yield('myTable', $myArray)

But i've get the error:

Error: Array to string conversion

That's because the yield function only accepts strings, right?

Background is: I want a table template which i can use dynamically for multiple purpose or multiple data, so i can use the same template for multiple tables and just pass the columns and content as array.

How can i pass an array to my yield section?

like image 382
Pascal Cloverfield Avatar asked Feb 17 '16 14:02

Pascal Cloverfield


2 Answers

You may use a separate file and include the file using @include while you may pass the data with a dynamic variable name so you'll be able to use that variable name in your included view, for example:

@include('view.name', ['variableName' => $array])

So, in the view.name view you can use/access the $array using $variableName variable and you are free to use any name for variableName.

So, in the separate view i.e: view.name, you may use a section and do whatever you want to do with $variableName.


Note: The problem was solved in the comment section but added as an answer here for the future reference so any viewer come here for similar problem will get the answer easily.

like image 151
The Alpha Avatar answered Nov 09 '22 23:11

The Alpha


@yield produce a section, like an include but with the included template defined from the children

@yield does not accept parameters, and it makes sense since the parent does not have to knows what children will implement.

If you want to pass parameters to the template, an @include probably suits better the case

@include('subview', ['parameter_name' => 'parameter_value'])

Otherwise a simple php variable declared by the parent and used by the children can work with a @yield (and also with @include)

@php
$my_var='my_value'
@endphp
@yield('my_section')

If you want to send data from children to the parent, you can do it at the parent declaration, where you add it:

@extends('parent_view',['parameter_name'=>'parameter_value'])
like image 3
Luca C. Avatar answered Nov 09 '22 22:11

Luca C.