Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I can't delete or restore a record on composite primary key

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

why is this happening?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading