@
@
@codeme2016-02-23 13:48:16
JavaScript
@codeme, 2016-02-23 13:48:16

How to fetch data from db using ajax + laravel?

I'm trying to extract the news and likes to the news in the controller, here is the controller. Tell me how to write Ajax correctly so that the likes on the page are updated automatically. I made the post method on Ajax, it adds data to the database, but I don’t understand how to extract it.

public function create()
    {
        $news = NewsModel::all();
        $like = DB::table('like')
            ->join('news', 'news.id', '=', 'like.news')
            ->first();

        return view('welcome', ['news' => $news, 'like' => $like]);
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Silm, 2016-02-23
@Silm

AJAX is no different from a regular request.
Create a method in the controller that will receive the necessary data and return it in JSON format. Create a get route for this method.
Make an AJAX request on the created route, get likes in response.

A
Andrzej Wielski, 2016-02-23
@wielski

$like = DB::table('like')
->join('news', 'news.id', '=', 'like.news')
->first();

Seriously? Terrible approach.
Read about Relations. hasOne will suit you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question