skip to Main Content

I have model with the following primary key

use HasFactory, SoftDeletes;
protected $table = 'requests';
protected $primaryKey = ['request_id', 'user_id'];
public $incrementing = false;
protected $keyType = 'string';

protected $fillable = [
    'request_id',
    'user_id',
];

protected $hidden = [
    'created_at',
    'updated_at',
    'deleted_at',
];

and I run the controller of the following

   public function store(int $request) {
        $user = Auth::user();

        $Request = Request::withTrashed()->firstOrCreate([
            'request_id' => $request,
            'user_id' => $user->id,
        ]);

        if (!$Request->wasRecentlyCreated) {
            $Request->deleted_at ? $Request->restore() : $Request->delete();
        }
    
    }

and everytime I run the controller I get error of

LOG.error: Illegal offset type { "userId": 1, "exception": {} }

why is this happening?

2

Answers


  1. Chosen as BEST ANSWER

    I found a work around by adding this line to the Model

    protected function setKeysForSaveQuery($query) {
            foreach ((array) $this->primaryKey as $key) {
                $query->where($key, '=', $this->original[$key] ?? $this->$key);
            }
    
            return $query;
        }
    

    it seems it causes a lot of errors sometimes but it works fine for me now


  2. Eloquent does not support composite keys:

    Eloquent requires each model to have at least one uniquely identifying "ID" that can serve as its primary key. "Composite" primary keys are not supported by Eloquent models.

    https://laravel.com/docs/10.x/eloquent#composite-primary-keys

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search