简体   繁体   中英

How to implement Laravel search system in the Blade view

I am building a CRUD product / categories system in Laravel. Each category HasMany products and each product belongsTo a category. Now, in my index product file I list in a table all the products, showing their data and their category.

This is the Productcontroller:

public function index()
{

    // $products = Product::all();

    $products = Product::orderBy('id')->paginate(15);
    return view('product.index', compact('products'));
}

And here is my blade view:

<div class="row">
            <div class="col-3">
                <h1>Products List</h1>
            </div>
            <div class="col-3">
                <div class="form-group">
                    <label for="exampleFormControlSelect1"><h2>Select Category</h2></label>
                    <select class="form-control" name="product_category" id="exampleFormControlSelect1">
                        {{-- @foreach ($categoryList as $category) --}}
                            {{-- <option>{{$category->slug}}</option> --}}
                         {{-- @endforeach --}}
                    </select>
                </div>
            </div>
        </div>
    </div>
    <div class="table-responsive">
            <table class="table align-items-center table-hover">
            <thead class="thead-light">
                <tr>
                    <th scope="col">Id</th>
                    <th scope="col">Category</th>
                    <th scope="col">Name</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($products as $product)
                    <tr>
                        <td>
                            <a href="{{ route('product.show', $product->id)}}">{{ $product->id }}</a>
                        </td>
                        <td>
                            @if(!empty($product->category))
                                {{ $product->category->name }}
                            @else
                                {{ 'No Category' }}
                            @endif
                        </td>
                        <td>
                            <a href="{{ route('product.show', $product->id)}}">{{ $product->name }}</a>
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>
    <hr>
    {{ $products->render() }}
</div>

Now, where I commented out the dropdown I want to give the user the possibility of selecting the single category so the products get filtered depending on the category selected. Whats is the best and fastest implementation for this? I checked the Laravel Scopes but it looks quite complicated to do. Also, this "search" function should be set up in the controller or in the API? Sorry for the confusion I have but I do not understand the best approach I can follow.

I recommend you to use the JavaScript library DataTable ( https://datatables.net/ ). All you need to do is:

Run:

npm install datatables.net-bs4

Then, in your bootstrap.js inside the try statement:

require('datatables.net-bs4');

In your app.scss

@import '~datatables.net-bs4/css/dataTables.bootstrap4.min.css';

Then, run

npm run dev

After that, go to your view and add the scripts at the bottom

$(document).ready( function () {
$('#table_id').DataTable();
} );

All you have to do now is add the "table_id" to the id of your table.

You can skip the first four steps by declaring the js library via cdn inside your head tag.

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">

<script type="text/javascript" charset="utf8"src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>

Finally I found this approach to be the easiest:

In my productController, I fetch the Products with their category using Eager loading

    if (request()->has('category')) {
        $products = App\Product::whereHas('category', function($query){
            $query->where('slug', request('category'));
        })->paginate(15);
        // dd($products);

    }

Then, in the view (product.index) I create a dropdown menu with anchor tags of the different categories. The backend sees the request (url) is carrying 'category', which is set as the slug of the single category, so the elements get fetched accordingly from DB and then filtered on the view. I also ordered them by ID and paginated them.

            <div class="dropdown">
                <button class="btn btn-secondary dropdown-toggle" type="button" id="triggerId" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    Categories
                </button>
                <div class="dropdown-menu">
                    @foreach ($categoryList as $category) 
                        <div class="dropdown-item">
                            <a href="/product/?category={{$category->slug}}">{{$category->slug}}</a>
                        </div>
                    @endforeach
                </div>
            </div>

// to paginate them
    {{ $products->render() }}

If anyone has a better approach feel free to comment!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM