Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
zulfikar-ditya opened this issue Jan 14, 2025 · 3 comments
Closed

Comments

@zulfikar-ditya
Copy link

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);
@crynobone
Copy link
Member

Hey there, thanks for reporting this issue.

We'll need more info and/or code to debug this further. Can you please create a repository with the command below, commit the code that reproduces the issue as one separate commit on the main/master branch and share the repository here?

Please make sure that you have the latest version of the Laravel installer in order to run this command. Please also make sure you have both Git & the GitHub CLI tool properly set up.

laravel new bug-report --github="--public"

Do not amend and create a separate commit with your custom changes. After you've posted the repository, we'll try to reproduce the issue.

Thanks!

@zulfikar-ditya
Copy link
Author

I just created the repository for reproduce the issue.
github

@crynobone
Copy link
Member

You should avoid resolving Eloquent when building SQL that doesn't follow Eloquent conversion:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants