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

wikorl's avatar
Level 13

Error when using Eloquent query

I'm messing arround with Laravel as API backend and Nuxt js as frontend. Authentication on client side works with Laravel Sanctum pretty fine. But when I trying to query the route "/api/trips" I am facing some, in my opinon strange behaviour.

Migration:

Schema::create('trips', function (Blueprint $table) {
            $table->string('uuid')->primary();
            $table->string('title');
            $table->dateTime('start');
            $table->datetime('end');
            $table->string('city')->nullable();
            $table->string('country');
            $table->decimal('budget', 10, 2)->nullable();
            $table->foreignId('user_id')->constrained()->onUpdate('cascade')->onDelete('cascade');

            $table->timestamps();
        });

Contoller "TripController"

namespace App\Http\Controllers;

use App\Http\Resources\TripRessource;

use App\Models\Trip;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class TripController extends Controller
{
    public function index()
    {
        $trips = Trip::where('user_id', Auth::id())->get();

        return response()->json($trips);
    }
}

Laravel throws the following error

Undefined array key 1 {"userId":1,"exception":"[object] (ErrorException(code: 0): Undefined array key 1 at /var/www/api/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php:602)

But when I am using the Query Builder in this way it returns every trip successfully.

$trips = DB::table('trips')
                ->where('user_id', Auth::id())
                ->get();

return response()->json($trips);

Where's the difference?

0 likes
6 replies
Tray2's avatar

You will see the difference if you change ->get() to ->toSQL() and dd the reuslt.

dd(Trip::where('user_id', Auth::id())->toSQL());
dd(DB::table('trips')
                ->where('user_id', Auth::id())
                ->toSQL());

They will most likely differ.

wikorl's avatar
Level 13

Trip model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

use App\Traits\Uuids;

use App\Models\User;

class Trip extends Model
{
    use HasFactory;
    use Uuids;

    protected $fillable = [
        'title',
        'start',
        'end',
        'city',
        'country',
        'budget',
        'user_id'
    ];

    protected $casts = [
        'start' => 'datetime',
        'end' => 'datetime',
        'budget' => 'decimal'
    ];

    protected $primaryKey = 'uuid';

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
tykus's avatar
tykus
Best Answer
Level 104

Problem with casting the decimal attribute perhaps; the correct format is decimal:<digits>, e.g. decimal:2

1 like
wikorl's avatar
Level 13

@tykus Thank you! The error message in the log files was completely missleading. I changed the cast to float and now it's working!

wikorl's avatar
Level 13

One record in the DB, created via factories looks like this

App\Models\Trip {#4316
     uuid: "07991de6-580b-311c-8007-f41cf5274cc4",
     title: "aut delectus",
     start: "2022-07-11 13:53:46",
     end: "2022-07-14 03:40:34",
     city: null,
     country: "Vanuatu",
     budget: null,
     user_id: 2,
     created_at: "2021-12-16 13:20:55",
     updated_at: "2021-12-16 13:20:55",
   }

App\Models\User {#4526
         id: 2,
         name: "Dipl.-Ing. Felix Fellner B.Eng.",
         email: "[email protected]",
         email_verified_at: "2021-12-16 13:20:55",
         #password: "yIXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi",
         two_factor_secret: null,
         two_factor_recovery_codes: null,
         #remember_token: "x1i3OJmjql",
         created_at: "2021-12-16 13:20:55",
         updated_at: "2021-12-16 13:20:55",
       },

Please or to participate in this conversation.