Justin
Justin

Reputation: 287

Livewire, Laravel - can I call a controller 'store' method from a Livewire component?

I have a Laravel controller with a 'store' method. i.e. store(Request $request).

For the view I want to embed a livewire component and then utilize the existing controller 'store' method (behind the scenes) from a livewire component method. Is this possible? Currently, I'm running into the problem that there is no Request object since I'm no longer making the call from the existing route/view (i.e. POST /orders).

public function oms_order()
// this method provides the POST /orders leveraging 
// Controllers\OrderController@store
{
    $this->refId = app('App\Http\Controllers\OrderController')->store($this->jsonOrder);
}

Argument 1 passed to App\Http\Controllers\OrderController::store() must be an instance of Illuminate\Http\Request, null given, called in D:\xampp\htdocs\jade\livewire_hpp\app\Http\Livewire\Oms.php on line 26

I can remove the 'Request $request' from the store method but then that breaks the standard Laravel POST /orders route.

I was hoping to use the existing laravel app as the backend/API and add the livewire bit for a demo. Any advice is welcome.

Upvotes: 5

Views: 5196

Answers (2)

owis sabry
owis sabry

Reputation: 161

oh man! , you should change your naming conventions , write the full name of the function , if you write the code correctly no need to write comments like this it's just one line code!

make a trait or helper function to do tasks between classes this is the best practice . controller is a part of MVC logic so, separation is required then if you do logic frequently just separate it in trait the use it in other classes

Upvotes: 0

I don't think it is a best practice to call a controller function from another class. If you want reusability, I suggest refactoring code by creating a separate class with a store method which accepts only required attributes and saves a record. Then you can use this method in multiple places. It is easier to test also. It is difficult to give an exact answer before seeing your store method.

Upvotes: 1

Related Questions