B. All
B. All

Reputation: 69

Laravel 5.2 Create function

i've been building a basic laravel CRUD system, with that i've made a basic create funciton but i want to make it so that if a record already exists in the database and u create the same record again that the Integer u put in the create form add's up by the already existing record example: u have a stock system with a product that has the ammount of 50, and u create the same product with the ammount of 40, and that the 40 add's up with the 50 so that in the database it will say 90. im not entirely sure how to do so.

This is the store function i've made for my application:

 public function store(Request $request)
{
    // Aantal = ammount (int)
    //Producten_Id = foreign_key from the Producten database table
    //Locaties_Id = foreign_key from the locaties database table

   Voorraad::Create($request->only(['aantal', 'Producten_Id', 'Locaties_Id']));
    //var_dump($request);

   return redirect(Route('voorraad.index'));
}

if u need more information just let me know and i'll add it to the question

Upvotes: 2

Views: 92

Answers (1)

Pawel
Pawel

Reputation: 3346

Assuming that you set up default value for this field in database structure, its as simple as:

$voorraad = Voorraad::firstOrCreate($request->only(['Producten_Id', 'Locaties_Id']);

$voorraad->increment('aantal', $request->aantal);

If you want to set default amount for new products in the controller do this instead:

$voorraad = Voorraad::firstOrCreate($request->only(['Producten_Id', 'Locaties_Id']);

if (! $voorraad->aantal) {
   $voorraad->aantal = 123; // default
}
else {
   $voorraad->aantal += $request->aantal;
}

$voorraad->save();

Generally speaking firstOrCreate method fetches from database record with passed attributes if it exists already or otherwise creates it. See in Laravel docs.

If you have any questions just ask in comments, I'll be happy to explain.

Upvotes: 1

Related Questions