Search code examples
phppostcontrollerlaravel

Call Controller Function from Laravel Routes.php


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

Solution

  • As suggested by 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.