Ad

Laravel Query Builder To Eloquent Builder

- 1 answer

How can I convert following Laravel DB Query Builder to Eloquent?

Is it possible to do Laravel Eloquent?

$reports = DB::table('clicks')
            ->select('offer_name', DB::raw('offer_name as offers, COUNT(id) as clicks, SUM(IF(status = 1, 1, 0)) as lead, SUM(IF(status=1, payout, 0)) as earnings'))
            ->groupBy('offer_name')
            ->get();
Ad

Answer

You can change on DB::table('clicks') to Eloquent Builder. select and groupBy is same for Eloquent.

Now make a model of clicks using command.

php artisan make:model Click

It'll create Click.php file in App folder. It looks like this as I mention below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Click extends Model
{
    protected $table = 'clicks';

}

Now your query looks like this.

$reports = \App\Click::select('offer_name', DB::raw('offer_name as offers, COUNT(id) as clicks, SUM(IF(status = 1, 1, 0)) as lead, SUM(IF(status=1, payout, 0)) as earnings'))
            ->groupBy('offer_name')
            ->get();
Ad
source: stackoverflow.com
Ad