Is it appropriate to create method in model like this...
Hi Laravers,
I am building a small eCommerce application.
In order to log order cancel reason, I added a method createCancelLog() in App\Order model
class Order extends Model {
...
public function cancelLog()
{
$this->hasOne(OrderCancelLog::class);
}
public function createCancelLog($request)
{
$this->cancelLog->create([
...
]);
}
...
}
And In OrderController,
class Order extends Controller
{
...
public function cancel(Request $request, Order $order)
{
$order->setCancelled();
$order->createCancelLog($request);
}
...
}
It gets the job done. But I am wondering if it is appropriate to add method in model in this way.
It's fine since you're not doing a tedious job inside the methods...
Just like we have it on the Eloquent relationship documentation (though it's data binding and modeling) But I feel you can have method in your model to.
Sure it works but that's not a MVC architectural pattern implementation. You add Controller-logic to the Model. This would even work on top of the (blade) View if you would like to make a point of it by calling the view directly from routes/web.
It's a good habit to respect the MVC pattern philosophy for your own good and call the C-class OrderController ;)
@vinsonyung I’d just have a cancel() method on the Order model. When you call it, it can set the status and also insert a row into the log table. Much nicer.