t0berius
1 month ago
112
3
Laravel

laravel redirect handling / increase coding style

Posted 1 month ago by t0berius

I'm working on a checkout page, this page consists of 3 controller actions (step1 / step2 /step3). In every controller action I would need to perform a few checks which are the same all the time.

I've created a method on the user model for this:

public function canPlaceOrder($product, $request)
{
    //check1
    if(x....)
        throw new \App\Exceptions\CanPlaceOrderException('error1');

    //check2
    if(y....)
        throw new \App\Exceptions\CanPlaceOrderException('error2');

    //check3
    if(z....)
        throw new \App\Exceptions\CanPlaceOrderException('error3');

    //add new checks here...
}

CanPlaceOrderException

namespace App\Exceptions;

use Exception;

class CanPlaceOrderException extends Exception
{

    public function report()
    {

    }
    public function render()
    {
        return back()->withErrors($this->getMessage());
    }
}

Now I'm using this method inside every controller action like:

Auth::user()->canPlaceOrder($product, $request);

Any idea how to get this solved and not using the same code lines in every one of the three controller actions? Is this a good style in general?

Please sign in or create an account to participate in this conversation.