A
A
Anton Vasiliev2021-03-01 01:10:23
Laravel
Anton Vasiliev, 2021-03-01 01:10:23

How to get one record from database via ajax using Laravel?

Code in routes.php

Route::get('/events?{id}', '[email protected]');

show function code in EventsController
public function show($id = 0)
{
  $events = Events::find($id);
  return view('events', ['events' => $events]);
}

ajax code (jquery)
var id = 9;
$.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                  }
});
$.get({
  url: '/events?'+id,
  method: 'get',
  success: function(result){
                    console.log()
   }
});

Started learning laravel (version 7).
The above code returns the entire page. Please tell me how to get record of one database row for example with id = 9 using ajax.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daria Motorina, 2021-03-01
@tambovvolk88

There are a lot of errors in the code
1) get-parameter is not added to ajax, it just comes out /events?9, not /events?id=9
2) wildcards in Laravel routing does not affect regular get-parameters, so it makes no sense to specify id as /events ?{id}, or form url like /events/9, then wildcard will make sense.
3) following from paragraph 2, no id will be automatically passed to the action, you need to get it yourself from the request object. Request object can be automatically injected into action arguments

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question