0

I want to pass an array of data into a partial, this partial is then being called from another view.

$posts = [
  "One",
  "Two",
  "Three"
]; 

return View::make('partials.post_template', $posts);

Inside the .blade.phpfile I am then doing

{{$posts}}

This returns and error of Undefined variable: posts Can someone tell me what I am doing wrong? Thanks

1
  • The laravel manual suggests a different writing: View::make('partials.post_template', array('posts' => $posts)); - And do you understand what undefined variable means? If so, what don't you understand you're doing wrong so far with such error message? Commented Apr 21, 2014 at 22:10

3 Answers 3

2

Can someone tell me what I am doing wrong?

The template you're using contains an undefined variable, here named posts.

It is important that you define all variables you intend to use with a view.

You pass such variables in form of an array where the key is the name of the variable and the value is the data that variable carries:

View::make('template-with-posts-variable', array('posts' => $posts));

It is the second parameter. The first parameter is the name of the template.

Sign up to request clarification or add additional context in comments.

2 Comments

Same error I'm afraid. Is this because I am passing this to a partial?
Well, you're having a sub-view then and you don't specify the variable for the subview. The error will not go away unless you define that variable for the view that has that variable (not for a different one).
1

Laravel does not send your variable as posts. If you have an array:

$data = [
    'posts' => [
        'One' => '1',
        'Two' => '2',
        'Three' => '3',
    ],
];

Then if you pass this data as you do pass $posts you will be able to access posts variable inside the view.

See docs.

Comments

1

You have to define a variable and pass it data like so

return View::make('partials.post_template')
    ->with('posts', $posts);

// or
return View::make('partials.post_template'
    ->withPosts($posts); // with a magic method

For more info see the official docs

6 Comments

Still getting an undefined error when trying to call $posts in the view.
Well, the syntax suggested in this answer is not by the book as well, which could be also cause of the problem.
@hakre What do you mean, it's officially supported, see "Passing Data To Views" on the docs
@afarazit: Yes exactly that part. The code in your answer looks like a mesh up of the different ways to do say mixed together. I don't think Laravel is that mature that this works that easily.
@joshuahornby10 just spotted my error, try the code again.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.