Search Result in Laravel

2

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>
                     @endforeach
                </ul> 
        </div>

Here I do the search according to your name

('#form').on('input',function(e)
        {
            e.preventDefault();
            exercise = $(this).serialize();
            $.post('/getSearch', exercise, function(search)

            {

                $('#data').html('');
                $.each(search, function (key,data){

                    $('#data').append(''+


                    '<li class="list-group-item" id="data"> <a id="name" href="/exercises/{{ $exercise->id }}" >'+data.name+'</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 }}" >'+data.name+'</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)
    {
        if($req->ajax())
        {
            $find= Exercise::where('name', 'LIKE','%' .$req->search. '%' )->get();
            return response()->json($find);

        }
    }

What can be wrong?

    
asked by Bella 13.04.2018 в 23:25
source

2 answers

0

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 }}" >'+data.name+'</a></li>'

It should be:

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

I think your problem is here:

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

data.id will come in response json from the server and with the value corresponding to each result

    
answered by 16.05.2018 в 22:54