0

So I went over this thread to figure out how to send data from controller to a view here.

However I am trying to pass multiple values with identical titles to the view and I cannot seem to figure out how to do this and still access them later.

I have a for loop that grabs all the films a user has in their database, this information is then stored into a array called $data

        $data = array();
        foreach ($films as $film)
        {               
            $title = $film->title;
            $description = $film->description;
            $url = $film->fileUrl;
            $data = array_add($data, 'title', $title);
            $data = array_add($data, 'description', $description);
            $data = array_add($data, 'url', $url);
        }
    $this->layout->content = View::make('profileFilms')->with($data);

This works but I cannot figure out how to access this information, I tried making each "film" its own array with all three data values and then adding that to the larger array and then passing that array to the view, which again worked but I cannot figure out how to access the data. if i use say {{$title}} it will grab one title, but I have no way of getting both.

How can I pass N number of films each with its title, description and url to a view so I can display them, and how can I display them?

Community
  • 1
  • 1
CMOS
  • 2,727
  • 8
  • 47
  • 83

2 Answers2

2

You are adding the values directly to the array once and that is it, because Laravels array_add only overwrites non existing keys.

You should do something like that (or use Eloquent):

<?php
$data = array();
foreach ($films as $film){
    $data['films'][] = array(
        'title' => $film->title,
        'description' => $film->description,
        'url' => $film->fileUrl
    );
}
$this->layout->content = View::make('profileFilms')->with($data);

Then you can access your films (Blade style):

@foreach($films as $film)
    {{$film['title']}}
@endforeach

If you want to use it like $film->title you can use the (object) typecast while assigning the array.

Of course, you could also pass $films directly like

$data = array(
    'films' => $films
);

Then you can access your films like you would in the controller. You can alsways use print_r and var_dump to see, what the variable really contains.

Alexander Taubenkorb
  • 3,031
  • 2
  • 28
  • 30
1
    $data = array();
    foreach ($films as $film)
    {               
        $row = array();
        $row = array_add($data, 'title', $film->title);
        $row = array_add($data, 'description', $film->description);
        $row = array_add($data, 'url', $film->fileUrl);
        // will send to view
        $data[] = $row;
    }
    $this->layout->content = View::make('profileFilms')->with($data);
Oscar M.
  • 1,076
  • 7
  • 9
  • I mentioned that I tried this, if I did it, how would I access it via view? $row->title? – CMOS May 16 '14 at 15:52