Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4, view composer with parameters?

Suppose I have this:

//controllers/BlogController.php
$data["post"] = $post = Blog::recent_post();
$data["posts_related"] = Blog::posts_related($post->category_id,5);
return View::make('blog.home', $data);

//views/sidebars/related.blade.php
@foreach($posts_related as $r)
<p>{{ $r->name }}</p>
@endforeach

//views/blog/home.blade.php
@include('sidebars.related')

My question is, how could I transfer:

$data["posts_related"] = Blog::posts_related($post->category_id,5);

To a view composer, since it seems I can't pass parameters to a view composer, but I can't be sure.

I appreciate any help!

like image 329
user2094178 Avatar asked Apr 23 '13 20:04

user2094178


1 Answers

In View Composer you can retrive data that passed to View.

View::composer('sidebars.related', function($view)
{
   //$data contains category_id
   $viewdata= $view->getData();

   //Retrive based on category_id
   $posts_related = Blog::posts_related($viewdata['category_id'],5);

   //pass related post to view
   $view->with('posts_related', $posts_related);
});

now everywhere you can use:

 View::make('sidebars.related')->with(array('category_id' => 6));
like image 153
Yahia Reyhani Avatar answered Oct 09 '22 20:10

Yahia Reyhani