I created a route & contronller:
Route::group(['prefix' => 'test'], function () {
Route::get('product/{id}', ['uses' => 'ProductController@getProduct']);
});
ProductController:
class ProductController extends MyController {
public $_params = null;
public function __construct(Request $request) {
$this->request = $request;
$this->_params = $request->all();
$options = array();
parent::__construct($options);
}
public function getProduct() {
dd($this->_params);
}
}
I requested: http://localhost/test/product/123
But the id = 123 not exist in $this->_params
CodePudding user response:
Request params are input data like POST data. To access route params you will need to make another class property like "$routeParams"
class ProductController extends MyController {
public $_params = null;
public $routeParams = null;
public function __construct(Request $request) {
$this->request = $request;
$this->_params = $request->all();
$this->routeParams = $request->route()->parameters();
$options = array();
parent::__construct($options);
}
public function getProduct() {
dd($this->routeParams);
}
}
I understand need to implement your logic on top of the Laravel, but I would suggest that you do that in some Services, Actions, Domain.... Maybe this can help: https://laravel-news.com/controller-refactor
You can try do it like basic controller from documentation and make some custom service for complex stuff.
class ProductController extends Controller
{
public function getProduct($id)
{
$productService = new ProductService($id);
//....
}
}
CodePudding user response:
If you want to get an array of the route parameters, you need to use $request->route()->parameters()
, not $request->all()
$request->all()
returns the query parameters for GET requests
CodePudding user response:
$request->all() only get parameter from header, body and URL but can't get parameter from route product/{id}
You should replace func getProduct to param id
public function getProduct($id) { dd($id); }
CodePudding user response:
İf you want all params in request use $request->all() method but you want only id in url $request->id