-1

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();
Fatih Can
  • 321
  • 4
  • 12
  • I presume `firstOrNew` takes care of _user applies a job post multiple times_ . – nice_dev Nov 24 '21 at 18:30
  • You should use two columns as primary keys.Check this url https://stackoverflow.com/questions/36332005/laravel-model-with-two-primary-keys-update – Zrelli Majdi Nov 24 '21 at 18:36
  • @ZrelliMajdi I tried in migration $table->primary(['user_id', 'posts_id']); but still inserts only 1 post not the others – Fatih Can Nov 24 '21 at 19:33
  • the first array to `firstOrNew` is the where conditions, so you are only searching to see if any `Applies` belongs to that user, not if that user and post id combination exists .. which is why a user can only have 1 `Applies` with what you have currently – lagbox Nov 24 '21 at 21:42
  • @lagbox Oh... So how is the proper way to solve this problem ? I did something but doesn't work at all . (Edited question) – Fatih Can Nov 24 '21 at 23:08

1 Answers1

2

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".

lagbox
  • 48,571
  • 8
  • 72
  • 83