Skip to content

Error when querying with model should be strict using select raw #1559

Closed
@zulfikar-ditya

Description

@zulfikar-ditya

Telescope Version

^5.2

Laravel Version

^11.31

PHP Version

8.3.11

Database Driver & Version

Mysql 8.0.40 Windows (x86, 32-bit)

Description

I want to query for total calculation of 2 colums

$currentPoint = CustomerPoint::where('customer_id', $customer->id)
            ->whereDate('expired_at', '>=', Carbon::now())
            ->orderBy('ordering')
            ->selectRaw('sum(`in`) - sum(`out`) as total_point')
            ->first();

When i run the method, i get this error.

The attribute [id] either does not exist or was not retrieved for model [App\Models\CustomerPoint].

laravel.log

[2025-01-14 11:59:29] local.ERROR: The attribute [id] either does not exist or was not retrieved for model [App\Models\CustomerPoint]. {"userId":1,"exception":"[object] (Illuminate\\Database\\Eloquent\\MissingAttributeException(code: 0): The attribute [id] either does not exist or was not retrieved for model [App\\Models\\CustomerPoint]. at C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Concerns\\HasAttributes.php:505)
[stacktrace]
#0 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Concerns\\HasAttributes.php(485): Illuminate\\Database\\Eloquent\\Model->throwMissingAttributeExceptionIfApplicable('id')
#1 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Model.php(1993): Illuminate\\Database\\Eloquent\\Model->getAttribute('id')
#2 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\telescope\\src\\FormatModel.php(25): Illuminate\\Database\\Eloquent\\Model->getKey()
#3 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\telescope\\src\\Watchers\\RequestWatcher.php(236): Laravel\\Telescope\\FormatModel::given(Object(App\\Models\\CustomerPoint))
#4 [internal function]: Laravel\\Telescope\\Watchers\\RequestWatcher->Laravel\\Telescope\\Watchers\\{closure}(Object(App\\Models\\CustomerPoint), 'currentPoint')
#5 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\framework\\src\\Illuminate\\Collections\\Arr.php(609): array_map(Object(Closure), Array, Array)
#6 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\framework\\src\\Illuminate\\Collections\\Collection.php(795): Illuminate\\Support\\Arr::map(Array, Object(Closure))
#7 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\telescope\\src\\Watchers\\RequestWatcher.php(234): Illuminate\\Support\\Collection->map(Object(Closure))
#8 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\telescope\\src\\Watchers\\RequestWatcher.php(202): Laravel\\Telescope\\Watchers\\RequestWatcher->extractDataFromView(Object(Illuminate\\View\\View))
#9 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\telescope\\src\\Watchers\\RequestWatcher.php(57): Laravel\\Telescope\\Watchers\\RequestWatcher->response(Object(Illuminate\\Http\\Response))
#10 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\framework\\src\\Illuminate\\Events\\Dispatcher.php(458): Laravel\\Telescope\\Watchers\\RequestWatcher->recordRequest(Object(Illuminate\\Foundation\\Http\\Events\\RequestHandled))
#11 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\framework\\src\\Illuminate\\Events\\Dispatcher.php(286): Illuminate\\Events\\Dispatcher->Illuminate\\Events\\{closure}('Illuminate\\\\Foun...', Array)
#12 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\framework\\src\\Illuminate\\Events\\Dispatcher.php(266): Illuminate\\Events\\Dispatcher->invokeListeners('Illuminate\\\\Foun...', Array, false)
#13 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php(152): Illuminate\\Events\\Dispatcher->dispatch('Illuminate\\\\Foun...')
#14 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Application.php(1190): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))
#15 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\public\\index.php(17): Illuminate\\Foundation\\Application->handleRequest(Object(Illuminate\\Http\\Request))
#16 C:\\Users\\zulfi\\Developer\\Laravel\\scan-dulu\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\resources\\server.php(23): require_once('C:\\\\Users\\\\zulfi\\\\...')
#17 {main}
"} 

But when i tried to use another method when i getting the query work with no issue

$currentPoint = CustomerPoint::where('customer_id', $customer->id)
            ->whereDate('expired_at', '>=', Carbon::now())
            ->orderBy('ordering')
            ->sum('in')
            - CustomerPoint::where('customer_id', $customer->id)
            ->whereDate('expired_at', '>=', Carbon::now())
            ->orderBy('ordering')
            ->sum('out');

This is me doing something wrong or the telescope have bug, There is no entry from /telescope for the related error.
Thanks in advance

Steps To Reproduce

customer_points table

Schema::create('customer_points', function (Blueprint $table) {
    $table->id();
    $table->foreignIdFor(Customer::class)->constrained();
    $table->integer('in')->unsigned()->default(0);
    $table->integer('out')->unsigned()->default(0);
    $table->string('ordering', 30);
    $table->timestamp('expired_at');
    $table->timestamps();
});

CustomerPointModel

#[ObservedBy(CustomerPointObserver::class)]
class CustomerPoint extends Model
{
    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [
        'customer_id',
        'in',
        'out',
    ];

    /**
     * Get the customer that owns the CustomerPoint
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class);
    }
}

customerController

**
 * Display the specified resource.
 */
public function show(Customer $customer)
{
    $customer->withCount('scans');

    $customer  = Customer::withCount('scans')
        ->findOrFail($customer->id);

    // $currentPoint = CustomerPoint::where('customer_id', $customer->id)
    //     ->whereDate('expired_at', '>=', Carbon::now())
    //     ->orderBy('ordering')
    //     ->selectRaw('sum(`in`) - sum(`out`) as total_point')
    //     ->first();

    $currentPoint = CustomerPoint::where('customer_id', $customer->id)
        ->whereDate('expired_at', '>=', Carbon::now())
        ->orderBy('ordering')
        ->sum('in')
        - CustomerPoint::where('customer_id', $customer->id)
        ->whereDate('expired_at', '>=', Carbon::now())
        ->orderBy('ordering')
        ->sum('out');

    return view("customer.show", compact("customer", "currentPoint"));
}

AppServiceProvider

/**
 * Register any application services.
 */
public function register(): void
{
    Model::shouldBeStrict(true);

    $aliasInstance = AliasLoader::getInstance();
    $aliasInstance->alias('Carbon', \App\Supports\Carbon::class);
    $aliasInstance->alias('Str', \App\Supports\Str::class);
    $aliasInstance->alias('Number', \App\Supports\Number::class);

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions