I have a function in my Orders_Controller
in Laravel called getOrders($user). It calls a raw DB query and builds a JSON array to return.
I cannot figure out how to call this function from within my routes file.
Basically I receive a POST in the routes, insert the new Order, then I want to call getOrders(user) from this Routes function to get all the existing Orders for the given user.
Can someone help me figure out how to call this function from within Routes.php?
Routes.php
//Handle a new order POST
Route::post('order', array('do' => function() {
...
... //HANDLE POST DATA AND INSERT NEW ORDER
...
//GET ALL ORDERS FOR THIS USER FROM ORDER CONTROLLER
$userOrders = Order_Controller::myOrders($thisUser);
}
order.php (in Controllers folder)
class Order_Controller extends Base_Controller
{
public function myOrders($user){
return DB::query("SELECT ...");
}
}
use App\Http\Controllers\UserController; Route::get('/user/{id}', [UserController::class, 'show']); When an incoming request matches the specified route URI, the show method on the App\Http\Controllers\UserController class will be invoked and the route parameters will be passed to the method.
$varbl = App::make("ControllerName")->FunctionName($params); to call a controller function from a my balde template(view page). Now i'm using Laravel 5 to do a new project and i tried this method to call a controller function from my blade template .
You can define a route to this controller action like so: Route::get('user/{id}', 'UserController@show'); Now, when a request matches the specified route URI, the show method on the UserController class will be executed. Of course, the route parameters will also be passed to the method.
As suggested from larauser you could move your myOrders() method to a model and call it statically. Here's an example
class Order extends Eloquent {
public static function myOrders($user)
{
// DB call here
}
}
Then in your route you could do
Route::post('order/(:num)', function($user)
{
$userOrders = Order::myOrders($user);
// Do stuff here
});
I'm guessing you're passing the user ID that's the reason i'm using (:num) in the route.
Hope that helps.
There is another way that I have used, maybe incorrectly, but it might work for you.
$userOrders = Controller::call('order@myOrders', array($thisUser))->content
For more information and how to use it check out the documentation for the Controller class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With