Home > Software design >  Laravel prevent data duplicate in database
Laravel prevent data duplicate in database

Time:11-25

I want to prevent data duplicate in database when user applies a job post multiple times.

I tried firstOrNew() like...

 $apply = Applies::firstOrNew(
        ['user_id' =>  Auth::id()],
        ['posts_id' =>  request('id')]);
        
    $apply->save();

But this time user can't apply other posts anymore .

Edit 1 I tried it but doesn't do anything.

$apply = Applies::firstOrNew(
        ['user_id' =>  Auth::id()] && ['posts_id' => request('id')],
        ['user_id' =>  request(Auth::id())],
        ['posts_id' =>  request('id')]);
        
    $apply->save();

CodePudding user response:

The first array is the "attributes", the where conditions for the look up. You would need to have the user_id and post_id in that array:

Applies::firstOrNew([
    'user_id' => ...,
    'post_id' => ...,
]);

This will cause it to search for that combination and only if it can't find it will it create a new (non-existing) model instance and fill it with those "attributes".

  • Related