Prabhu
Prabhu

Reputation: 57

How to stop executing a method in controller from laravel observer

In laravel, I am creating a record i.e. adding a new bus. And i am trying Laravel Observer to check write the logic. Here i've checked if bus with same registration number already exists or not and if no, it should insert the bus. But if the bus is already created or exists, it shouldn't create a new record and should send an error message.

This is my BusController

public function store(Request $request)
{
    $request->validate([
        'bus_type_id' => 'required',
        'route_id' => 'required',
        'reg_num' => 'required',
        'seat_capacity' => 'required',
    ]);

    Bus::create($request->all());

    return redirect()
        ->route('bus')
        ->with('success','New Bus Added successfully.');
}

This is my BusObserver where it check if reg_num exists or not

public function creating(Bus $bus)
{
    $count = Bus::where('reg_num', '=' ,$bus->reg_num)->count();

    // dd($count);
    if($count == 1) {
        // avoid inserting and show error message
    }
}

When i do dd($count); it shows the number of buses with same reg_num which is what i wanted. but i want not to execute create() method in Controller. I also know we can't redirect from Observer. So, how should i perform this?

Upvotes: 0

Views: 608

Answers (1)

mrhn
mrhn

Reputation: 18956

The way the exceptions handler works, is it catches all your exceptions and transform it into the errors you want. Therefor you can throw exceptions from anywhere in your application (redirects will only work in context of http calls) and it will be handled by the exceptions handler.

Create your own exception.

class DuplicateBusException extends Exception {
    public function __construct() {
    }
}

public function creating(Bus $bus)
{
    $count = Bus::where('reg_num', '=' ,$bus->reg_num)->count();
    // dd($count);
    if($count == 1) {
        throw new DuplicateBusException();
    }
}

Now you can in app/Exceptions/Handler.php, make the logic that should handle it appropriately.

public function render($request, Exception $exception)
{
    if ($exception instanceof DuplicateBusException) {
        //your logic for an example an redirect
        return redirect()->back();
    }

    return parent::render($request, $exception);
}

Upvotes: 2

Related Questions