How to access url segment in controller in laravel 5.2 - php

I am working in Laravel 5.2 and i want to access URL segments in my controller. I am using
echo Request::segment(2);
but nothing is print. How can i get values from url in controller.

In laravel 5.2 you can do it this way..
echo request()->segment(2);
request() is one of the several helper functions provided in Laravel 5.2. It returns the current request object thus you don't need use statement for the facade on the top of your class.

In Laravel 7, I am using this to get segments
public function my_function(Request $request )
{
// By using this, we can get the second segment in route
// Example: example.com/hh/kk
$segment = $request->segment(2);
// By using this we will get "kk"
}

Related

"Undefined type 'App'" in api.php Laravel

I'm using Laravel 8.53 and Vuejs.
I want to set language for specific controller based on api parameter. (to send password reset email in desired language)
I have this route in api.php which works:
Route::post('forgot-password', [NewPasswordController::class, 'forgotPassword'])->name('password.reset');
Now I wanted to create something like this:
Route::post('forgot-password/{locale}', function ($locale) {App::setLocale($locale);}, [NewPasswordController::class, 'forgotPassword'])->name('password.reset');
Now when I send to /api/forgot-password/en I get 200 OK but no response.
My VS Code is showing me this error: Undefined type 'App'.
Do I need to define "App" in api.php? How?
I am not sure if it's correlated but maybe the problem is in different place. You passing three parameters to post method. According to laravel docs you should pass only two. In this case you pass callback, or you pass controller path with method. Try to move App::setLocale() to your controller method and use your first syntax. Remember to import App facade before using it.
// api.php
Route::post('forgot-password', [NewPasswordController::class, 'forgotPassword'])->name('password.reset');
// NewPasswordController.php
use \App;
class NewPasswordController {
public function forgotPassword( $locale ) {
App::setLocale( $locale );
/* rest of code */
}
}

Laravel get method parameters cannot be fetched

I faced a weird issue in Laravel today, the version am using is Laravel 5.5 and I have defined a route as below in the application.
Route::get('getplaylist/{playlistid}/{page}', 'Mycontroller#getplaylist');
And in my controller am trying to fetch the parameters, weirdly
dd($request->all()); // results in empty array []
whereas the below one works,
dd($request->playlistid);
Any help would be appreciated on what is happening behind the scenes. The issue am facing is am not able to validate the request since an empty '[]' array is resulted.
Route parameters, like playlistid and page in your example, can be used with the $request->route() method.
Example:
$request->route('playlistid')
You can also fetch all route parameters using $request->route()->parameters().
As #erikgaal already mentioned, these are route parameters, not request parameters.
But, as is written in the docs, it is one of the most basic and core parts of Laravel, that these route parameters get injected into the controller method. Therefore, with your route:
class Mycontroller
{
public function getplaylist(Request $request, $playlistid, $page)
{
// Do stuff
}
}

Get the multiple query ? parameters passed in laravel url

AM using angular4 with laravel and am trying to append query parameters and read them in laravel as follows
My http request is get
The url after adding parameters look like
http://localhost:8000/user-management/users?global_filter=12
?paginator=10?page=0?sortfield=username|asc
Now in my laravel routes i have
Route::group(['prefix'=> 'user-management','middleware'=>['auth:api']], function() {
Route::resource('users', "UsersController");
});
Now in my usersController i have
class UsersController extends Controller{
public function index(Request $request)
{
return $request->all();
}
Now the above returns
global_filter:"null?paginator=10?page=0..."
The problem comes when i want to access the paginator value which is null as above.
How do i go about this so that i can be able to retrieve attached values of globalfilter, paginator and sortfield.
I still would wish to continue using the route resource
According to the Url in your question http://localhost:8000/user-management/users?global_filter=12?paginator=10?page=0sortfield=username|ascz it seems you wrongly add ? twice and it caouse the first queryString eliminated and just second part detected, I suggest you use & instead of the second ?.

Laravel call controller based upon query string or post variables

I am creating APIs for an app. Now app developer wants me to create a fixed base url and pass the ROUTE NAME (Which will point to controller function) as POST variable. Example:
http://example.com/Api
and POST variables like:
action=>'ROUTE_NAME'
But in laravel we can define the routes based upon the url parts as:
http://example.com/Api/ROUTE_NAME
I have tried using a single controller and loading the other controllers based upon SWITCH statements. But that doesn't seem to be a standard practice as i need to add switch condition every time I'll create a new API. Also middleware will not work on the loaded controllers dynamically.
Is there a way in laravel to achieve this? I am using laravel 5.4
You could implement a middleware that listens on the /Api route, which gets the ROUTE_NAME from the $request, then you could use the Route() helper function to find the url of that named route, then redirect the request to that route.
Something like:
// Generating ROUTE_NAME url...
$url = route($request->route_name);
// Redirect to that route...
return redirect()->route($url);
Obviously you'll need to add code to handle if it doesn't find a route etc, maybe return a json response back with a proper error code etc.

How to use the request route parameter in Laravel 5 form request?

I am new to Laravel 5 and I am trying to use the new Form Request to validate all forms in my application.
Now I am stuck at a point where I need to DELETE a resource and I created a DeleteResourceRequest for just to use the authorize method.
The problem is that I need to find what id is being requested in the route parameter but I cannot see how to get that in to the authorize method.
I can use the id in the controller method like so:
public function destroy($id, DeletePivotRequest $request)
{
Resource::findOrFail($id);
}
But how to get this to work in the authorize method of the Form Request?
That's very simple, just use the route() method. Assuming your route parameter is called id:
public function authorize(){
$id = $this->route('id');
}
You can accessing a Route parameter Value via Illuminate\Http\Request instance
public function destroy($id, DeletePivotRequest $request)
{
if ($request->route('id'))
{
//
}
Resource::findOrFail($id);
}
Depending on how you defined the parameter in your routes.
For my case below, it would be: 'user' not 'id'
$id = $this->route('user');
Laravel 5.2, from within a controller:
use Route;
...
Route::current()->getParameter('id');
I've found this useful if you want to use the same controller method for more than one route with more than one URL parameter, and perhaps all parameters aren't always present or may appear in a different order...
i.e. getParameter('id')will give you the correct answer, regardless of {id}'s position in the URL.
See Laravel Docs: Accessing the Current Route
After testing the other solutions, seems not to work for laravel 8, but this below works
Route::getCurrentRoute()->id
assuming your route is
Route::post('something/{id}', ...)
I came here looking for an answer and kind of found it in the comments, so wanted to clarify for others using a resource route trying to use this in a form request
as mentioned by lukas in his comment:
Given a resource controller Route::resource('post', ...) the parameter you can use will be named post
This was usefull to me but not quite complete. It appears that the parameter will be the singular version of the last part of the resource stub.
In my case, the route was defined as $router->resource('inventory/manufacturers', 'API\Inventory\ManufacturersController');
And the parameter available was manufacturer (the singular version of the last part of the stub inventory/manufacturers)
you will get parameter id if you call
request()->route('id')
OR
$this->route('id')
if you're using resource routing, you need to call with the resource name
// eg: resource
Route::resource('users', App\Http\Controllers\UserController::class);
$this->route('user')
in Terminal write
php artisan route:list
to see what is your param name
Then use
$this->route('sphere') to get param

Categories