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 ?
Asked
Active
Viewed 391 times
0
1 Answers
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
-
Exactly what wanted to mention – Yehia Awad Nov 29 '15 at 14:04
-
thnx @jedrzej this will do it for me, also if apart from this approach, can i use two models in one controller function – robinhood Nov 29 '15 at 15:11
-
The only answer I can give is: it depends. For sure it is technically possible, but it all depends on your design and what you want to achieve. – jedrzej.kurylo Nov 29 '15 at 16:51