0

Currently I am developing a small to middle level application in laravel I came across middleware in laravel, My question is Can i use middleware for making changes in my table for eg, In my application(Canteen Management System), When user orders something from the menu and make request for order then before inserting the order into the model table i want to subtract the order amount from his balance. Reason i am thinking of doing this is because balance attribute is a part of user table and order amount is another part of Order table and i am not being able to develop any data relation between them (but I derive many to one relation between them). So i am not thinking of doing only this thing using data relationship , So that's when i come accross middleware. So help me about this, also Can i use two model in one controller function ?

jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107
robinhood
  • 26
  • 4

1 Answers1

1

Middleware is executed before or after a request is processed. It's not a place where you should execute business logic you're describing.

A tool that better suits your needs could be Eloquent's model observers - you can read more about them here: http://laravel.com/docs/5.0/eloquent#model-observers

In your case, you could register a OrderObserver that would reduce user's balance after an order is placed. A basic example:

class OrderObserver {
  public function created($order) {
    $user = $order->user;
    $user->balance = $user->balance - $order->quantity;
    $user->save();
  }
}
jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107