Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DenMette's avatar

Howto convert eloquent query to resource

Hi

I'm working on a small application for a youth organisation. But I'm stuck in my mind ...

select kids.id, kids.cash, kids.forename, kids.surname, (kids.cash - SUM(IFNULL(sub.total, 0))) as money from  ( select histories.kid_id, (COUNT(histories.item_id) * items.price) AS total from `histories` inner join `items` on `histories`.`item_id` = `items`.`id` group by `histories`.`kid_id`, `histories`.`item_id`, `items`.`price` ) AS sub  right join `kids` on `sub`.`kid_id` = `kids`.`id` group by `kids`.`id`, `kids`.`forename`, `kids`.`surname`, `kids`.`cash` order by `kids`.`forename` asc, `kids`.`surname` asc
        $kids = Kid::selectRaw('kids.id, kids.cash, kids.forename, kids.surname, (kids.cash - SUM(IFNULL(sub.total, 0))) as money')
            ->from(DB::raw(' ( ' . $subQuery->toSql() . ' ) AS sub '))
            ->mergeBindings($subQuery->getQuery())
            ->rightJoin('kids', 'sub.kid_id', '=', 'kids.id')
            ->groupBy('kids.id', 'kids.forename', 'kids.surname', 'kids.cash')
            ->orderBy('kids.forename')
            ->orderBy('kids.surname')
            ->get();

So the children's can put there money into the bank, and in the evening the can buy a drink and/or a snack. The selling will put a new record in the history table.

The query works fine, and the application does what it requires todo, but I would like to create a bulma/vue/api driven application instead of a jquery/bootstrap application. But the transformation isn't clear for me.

How can I put the query above into a resource/resource collection?

see my eloquent model for Kid

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Kid extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'forename',
        'surname',
        'cash',
    ];

    protected $appends = [
        'name',
        'money',
    ];

    private $money = 0;

    public function name()
    {
        return sprintf('%s %s', $this->forename, $this->surname);
    }

    public function getNameAttribute()
    {
        return $this->name();
    }

    public function getMoneyAttribute($value)
    {
        if (empty($value) && empty($this->money)) {
            return 0;
        } else {
            if (! empty($value) && empty($this->money)) {
                $this->money = $value;
            }
        }

        return $this->money;
    }

    public function histories()
    {
        return $this->hasMany(History::class);
    }
}
0 likes
1 reply
jlrdw's avatar
jlrdw
Best Answer
Level 75

When I am dealing with larger sql, or if I have to start messing around with selectRaw, I usually just use built in getPdo()

I gave an example here: https://laracasts.com/discuss/channels/guides/getpdo-usage

Also @Cronix gave good explaination here https://laracasts.com/discuss/channels/eloquent/writing-all-queries-directly-vs-model-relations

Another discussion: https://laracasts.com/discuss/channels/laravel/coverting-ms-access-queries-to-laravel-query-builder

Another good discussion: https://laracasts.com/discuss/channels/general-discussion/sql-injection-2

1 like

Please or to participate in this conversation.