5
votes

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 ...");
    }
}
5

5 Answers

6
votes

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.

4
votes

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.

2
votes

the myOrders function should probably go in your orders model since its working with data access. Then, to call it you'd do Orders::myOrders($user).

2
votes

Easier way is call controller as class

Route::post( 'post', function() use ($user) {
  return (new OrderController)->myOrders($user);
});

1
votes

Routes.php

//Handle a new order POST
Route::post('orders/(:num)', function($user) {
    ...
    ... //HANDLE POST DATA AND INSERT NEW ORDER
    ...
});

Route::get('orders', function($user) {
   //GET ALL ORDERS FOR THIS USER FROM ORDER MODEL
   $userOrders = Order::myOrders($user)->get();
});

application/models/Order.php

class Order extends Eloquent
{
    public function myOrders($user_id)
    {
        return Order::where_user_id($user_id);
    }
}