Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Load method in another controller without changing the url

Tags:

I have this route: Route::controller('/', 'PearsController'); Is it possible in Laravel to get the PearsController to load a method from another controller so the URL doesn't change?

For example:

// route:
Route::controller('/', 'PearsController');


// controllers
class PearsController extends BaseController {

    public function getAbc() {
        // How do I load ApplesController@getSomething so I can split up
        // my methods without changing the url? (retains domain.com/abc)
    }

}

class ApplesController extends BaseController {

    public function getSomething() {
        echo 'It works!'
    }

}
like image 344
enchance Avatar asked Jun 10 '13 23:06

enchance


People also ask

What is invoke controller in Laravel?

Our controllers will look something like this:- and… Now what about this __invoke function. __invoke function is a type of magic method which will be called when you try to call an object as a function. So in simple words this function makes our class to be called as a function.

Can we apply middleware on controller in Laravel?

Laravel incorporates a middleware that confirms whether or not the client of the application is verified. If the client is confirmed, it diverts to the home page otherwise, it diverts to the login page. All controllers in Laravel are created in the Controllers folder, located in App/Http/Controllers.


2 Answers

You can use (L3 only)

Controller::call('ApplesController@getSomething');

In L4 you can use

$request = Request::create('/apples', 'GET', array());
return Route::dispatch($request)->getContent();

In this case, you have to define a route for ApplesController, something like this

Route::get('/apples', 'ApplesController@getSomething'); // in routes.php

In the array() you can pass arguments if required.

like image 67
The Alpha Avatar answered Sep 24 '22 18:09

The Alpha


( by neto in Call a controller in Laravel 4 )

Use IoC...

App::make($controller)->{$action}();

Eg:

App::make('HomeController')->getIndex();

and you may also give params

App::make('HomeController')->getIndex($params);
like image 31
Joeri Avatar answered Sep 25 '22 18:09

Joeri