Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ...");
    }
}
like image 608
jamis0n Avatar asked Dec 02 '12 21:12

jamis0n


People also ask

How can we call a function in controller route in Laravel?

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.

How do you call a page with a controller in Laravel?

$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 .

What is route in Laravel controller?

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.


2 Answers

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.

like image 100
afarazit Avatar answered Sep 30 '22 03:09

afarazit


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.

like image 27
mattl Avatar answered Sep 30 '22 03:09

mattl