Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Request object from route in Laravel?

Following is my routes where I am calling my Controller directly in route.

How can I pass Request $request to my getBlog Function.. Or is there any way to directly get $request object in my getblog function of controller ???

$artObj = App::make('App\Http\Controllers\Front\ArticleController'); 
return $artObj->getBlog($id);

Code in Routes:

Route::get('/{slug}', function($slug) {
    // Get Id and Type depending on url 
    $resultarray = App\Model\UrlAlias::getTypefromUrl($slug);
    if(!empty($resultarray)) {
        if($resultarray[0]['type'] == 'article') {
            $id = $resultarray[0]['ref_id'] ;
            $artObj = App::make('App\Http\Controllers\Front\ArticleController');
            return $artObj->getBlog($id);
        } else {
            return Response::view("errors.404", $msg, 400);
        }
    } else {
        return Response::view("errors.404", array(), 400);
    }

});
like image 429
Satish Upadhyay Avatar asked Sep 05 '25 12:09

Satish Upadhyay


2 Answers

You can do in the head of the routes.php file:

use Illuminate\Http\Request; 

And then in the beginning of your route:

Route::get('/{slug}', function($slug, Request $request) {

And the $request will be available to you. But that is extremely bad practice. What you should do - is move the whole logic into the controller like that:

Route::group(['namespace' => 'Front'], function(){
   Route::get('/{slug}', 'ArticleController@methodName'); 
});

and then you can use the Request class in your controller class and the controller method:

<?php 

namespace App\Http\Controllers\Front

use Illuminate\Http\Request; 

class ArticleController 
{ ...

   public function methodName(Request $request){
     ...function implementation...
   }

  ...
}
like image 192
naneri Avatar answered Sep 09 '25 03:09

naneri


The Request is a global variable, you can access it anywhere with either php code or even some helper Laravel functions.

Just use request() and it's the same as passing the request as an object inside a variable through a function. (It's equivalent to the Request $request variable received).

It improved readability also. Just remember you can't change request objects directly, you'd better use request()->merge(['key' => 'newValue']);

like image 39
edu.nicastro Avatar answered Sep 09 '25 03:09

edu.nicastro