2

I have a dropdown that I´m using to filter images by category. My first problem is that I want the selected choice to be selected after the filter, how can I do that?

This is my first time using Laravel and I wonder if I´m going in the right direction with my solution (now I have the same code in two functions, I´m planning on fixing that), but I can´t really figure out the best way of doing this. Can I have a function that takes either a category or null?

     <div class="dropdown">
        <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" value="">Show all</button>
        <ul class="dropdown-menu" role="menu">
            @foreach ($categories as $category)
               <li value="{{ $category->id }}"><a href="{{$category->id}}">{{ $category->name }}</a></li>
            @endforeach
        </ul>
     </div>

routes

Route::get('/', array('uses' => 'MyController@index'));
Route::get('/{category?}', array('uses' => 'MyController@filter'));

controller

public function index()
{
    $images = Image::all();

    $categories = ..\Models\Category::all();

    return View::make('index', array('images' => $images, 'categories' => $categories));
}

public function filter($category){

    $images = Image::where('category_id', '=', $category);

    $categories = ..\Models\Category::all();

    return View::make('index', array('images' => $images, 'categories' => $categories));

}
ana
  • 475
  • 4
  • 10
  • 21

1 Answers1

1

In your view, add a condition to check if the current category in the loop is the selected one.

@foreach ($categories as $category)
    @if($category->id == Input::get('category')
           // echo category as selected
    @else
           // echo category
    @endif
@endforeach

You might need to use html <select>.

You can use the same approach to combine the two function.

if(Input::has('category'))
     $images = Image::where('category_id', '=', $category);
else
  $images = Image::all();

This should work since your are using optional route parameter.

Update:

Use select as follows:

@foreach ($categories as $category)
    <select onchange="filter(this.value)">
         @if($category->id == Input::get('category')
             <option selected="selected" value="{{ $category->id }}">{{ $category->name }}</option>
         @else
              <option value="{{ $category->id }}">{{ $category->name }}</option>
         @endif
   </select>
@endforeach

Using the onchange attribute a javascript function will be called, then you can use redirect.

<script>
    function filter(id)
    {
        window.location.href = {{ URL::action('Controller@filter') }} + '/' + id;
</script>

where filter is the function in your controller.

Mahozi
  • 353
  • 1
  • 2
  • 10
  • Thank you for your answer, but I can´t get it to work. I´ve tried with – ana Feb 03 '15 at 12:43