Search Result in Laravel


Doing a search in Laravel, it gives me the search well in terms of name but not in ID.

That is to say.

This is the list of objects

<div class="panel-body-exercises">
             <h1 class="hidden">List of Exercise </h1>  
                <ul class="list-group">

                    <li class="list-group-item" id="data"></li>
                    @foreach($exercises as $exercise)

                        <li class="list-group-item" > 
                        <a id="name" href="/exercises/{{ $exercise->id }}" >  {{ $exercise->name}}</a></li>

Here I do the search according to your name

            exercise = $(this).serialize();
            $.post('/getSearch', exercise, function(search)


                $.each(search, function (key,data){


                    '<li class="list-group-item" id="data"> <a id="name" href="/exercises/{{ $exercise->id }}" >''</a></li>'+  '');



It gives me the result well, but when I click on it I get ID of another object and not the one indicated. As if

 <a id="name" href="/exercises/{{ $exercise->id }}" >''</a> Tiene algún error.

This is my controller, where does the search.

public function search(Request $req)
        $exercises= Exercise::all();
        return view ('exercises.index', compact ('exercises'));

    public function getSearch (Request $req)
            $find= Exercise::where('name', 'LIKE','%' .$req->search. '%' )->get();
            return response()->json($find);


What can be wrong?

asked by Bella 13.04.2018 в 23:25

2 answers


If the link you are generating with what you bring from your ajax you should use the id of that data and not the laravel one, that is:

Instead of:

'<li class="list-group-item" id="data"> <a id="name" href="/exercises/{{ $exercise->id }}" >''</a></li>'

It should be:

'<li class="list-group-item" id="data"> <a id="name" href="/exercises/''" >''</a></li>'
answered by 14.04.2018 в 00:51

I think your problem is here:

 <li class="list-group-item" id="data"> <a id="name" href="/exercises/{{ $exercise->id }}" >''</a></li>'+  '');

{{ $exercise->id }} this code is referring to the same php objs.

and when you are rendering with javascript it will always have the same value.

You should put:

<li class="list-group-item" id="data"> <a id="name" href="/exercises/' +'" >''</a></li>'+  ''); will come in response json from the server and with the value corresponding to each result

answered by 16.05.2018 в 22:54