Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: Calling routes internally

Is there a way, in Laravel 5, to call routes internally/programmatically from within the application? I've found a lot of tutorials for Laravel 4, but I cannot find the information for version 5.

like image 996
vcardillo Avatar asked May 26 '16 22:05

vcardillo


People also ask

How many types of routes are there in Laravel?

Route Parameters Laravel provides two ways of capturing the passed parameter: Required parameter. Optional Parameter.


1 Answers

Using laravel 5.5, this method worked for me:

$req = Request::create('/my/url', 'POST', $params);
$res = app()->handle($req);
$responseBody = $res->getContent();
// or if you want the response to be json format  
// $responseBody = json_decode($res->getContent(), true);

Source: https://laracasts.com/discuss/channels/laravel/route-dispatch

*note: maybe you will have issue if the route you're trying to access has authentication middleware and you're not providing the right credentials. to avoid this, be sure to set the correct headers required so that the request is processed normally (eg Authorisation bearer ...).

UPDATE: i've tried this method with laravel 8 and it works but if you're using PHP version 8.0 you might need to call opcache_reset(); before this line $req = Request::create('/my/url', 'POST', $params); to avoid an error.

see guzzlehttp/guzzle dosn't work after update php to php 8 for more info

like image 60
erwan Avatar answered Sep 24 '22 07:09

erwan