R
R
runprogr2019-12-26 22:46:11
Laravel
runprogr, 2019-12-26 22:46:11

How to properly use laravel + ajax?

For example forum. We need to implement the functionality of likes / dislikes to posts. Accordingly, it is necessary that when you click on the like button, the page does not reload, but an ajax request occurs. (All other functionality of the site works without ajax)
Questions
1) What is the correct route to use for such a request? web or API?
2) Which controller should the route refer to? On a regular one, or should I create some kind of special controller for ajax requests?
3) The very logic of likes. When you click on the like button, we pass the post id and user id in json format -> (write the line to the database) -> return the total number of post likes in json format. When pressed again, the operation is repeated, only the line is not added, but removed from the database. All right?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
khariv2907, 2019-12-27
@runprogr

1. If you really have to choose, then web is better
2. A separate controller is not needed. I create a new action in the controller I need with the ending "function ***Ajax()".
Also add a middleware that will check if this is an Ajax request (Request:: ajax ())

A
Andrey Suha, 2019-12-26
@andreysuha

1. No difference
2. No difference
3. You know better

Y
Yuri Kulaxyz, 2019-12-27
@Kulaxyz

Everything is described correctly, you can safely do it. There will be no difference between web and api. And with controllers, it's a matter of taste, I would do it in the post controller so that the ajax controller does not turn into a trash can when other requests not related to posts appear.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question