David February 2016

Order By Flyer Likes Laravel 5.2

I want to order travel flyers by how many likes a travel flyers has. I already have the flyers and likes table. I just dont know how would I count the flyers like and order them by highest when likwe tag is clicked on. As u can see, I already have a like counter for each flyer with the thumbs up icon enter image description here

Flyers Table:

Schema::create('flyers', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('title');
            $table->string('excerpt');
            $table->text('description');
            $table->timestamps();
});

Likeable Table:

( 'likeable_id' is the flyers id, and 'likeable_type' is from what model the like was placed, for example if a person liked a flyer it would be App\Flyer, or if a person liked an image it would be App\Image )

Schema::create('likeable', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('likeable_id');
            $table->string('likeable_type');
            $table->timestamps();
});

This is the OrderByController.php

As you can see I already have order by date asc, and desc

class OrderByController extends TravelFlyersController {

    /**
     * @param Flyer $flyer
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function travelDateAsc(Flyer $flyer)
    {
        $flyer = Flyer::orderBy('created_at', 'asc')->paginate(15);

        return view('travelflyers.index', ['flyer' => $flyer]);
    }


    /**
     * @p        

Answers


Yurich February 2016

I can make a mistake, but that's something kind of

-- edited --

$flyers = Flier::has('flyers', '>=', 1)
        ->select(\DB::raw('flyers.id, count(flyers.id) as likes, users.id'))
        ->join('likeable', 'users.id', '=', 'likeable.user_id')
        ->join('flyers', 'likeable.flier_id', '=', 'flyers.id')
        ->groupBy('users.id')
        ->orderBy('likes', 'desc')
        ->get();

Post Status

Asked in February 2016
Viewed 3,004 times
Voted 10
Answered 1 times

Search




Leave an answer