How can I get segment for current page in Laravel 5? - php

I have URL like this /project/1
How can I get param 1
I need it variable in another controller for another route....
here is examle:
route 1:
Route::get('project/{id}',array(
'as' => 'projectID',
'uses' => 'FirstController#someMethod'
));
route 2:
Route::post('another/route',array(
'as' => 'another',
'uses' => 'SecondController#anotherMethod'
));
I need to get inside anotherMethod id param from project/{id}... I tried like this return Request::segment(2); but it will return just segments from this route: another/route...
Any solution?

You can try this:
Controller:
public function index(Request $request){
return $request->segment(2); //set the segment number it depends on you
}

public function someMethod(Request $request)
{
// If you know the segment number
$id = $request->segment(2);
// If you know the parameter name
$id = $request->route('id');
// If you only know it's the last segment
$segments = $request->segments();
$id = array_pop($segments);
}

Related

How to show id in Resource Routes url?

Update:
This line of code in the frontend was the culprit:
<inertia-link v-if="options.edit" :href="'/admin/gallery/edit/1'">
I had to change it to:
<inertia-link v-if="options.edit" :href="'/admin/gallery/1/edit'">
to make it comply with the laravel resource format for edit, provided by #Babak.
Original Post:
How would I transform this route in web.php:
Route::get('/admin/gallery/edit/{id}', function ($id) {
$data = Gallery::find($id);
return inertia('backend/cms-gallery-edit', ['data' => $data]);
});
to a resource route with its resource controller function:
Route::resource('/admin/gallery', GalleryController::class);
GalleryController.php:
public function edit($id)
{
$data = Gallery::find($id);
// assign id to end of route
return inertia('backend/cms-gallery-edit', ['data' => $data]);
}
Edit:
I've tried both approaches of #Babak's answer, which work for index and create routes but the edit route still throws a 404. It is the only route encompassing an id.
web.php:
Route::resource('/admin/gallery', GalleryController::class)->only('index', 'create', 'edit');
GalleryController.php:
public function edit($gallery)
{
$data = Gallery::find($gallery);
return inertia('backend/cms-gallery-edit', ['data' => $data]);
}
Inertia passes the id from the frontend via href:
<inertia-link v-if="options.edit" :href="'/admin/gallery/edit/1'">
Browser shows:
GET http://127.0.0.1:8000/admin/gallery/edit/1 404 (Not Found)
There is a fixed structure for laravel resource route method, you can see full list here. For edit page, it will generate something like '/admin/gallery/{gallery}/edit'
You can write it like below:
In your web.php file:
Route::resource('/admin/gallery', GalleryController::class)->only('edit');
And in your controller, name of the resource must be the same as your function's parameter.
public function edit($gallery)
{
$data = Gallery::find($gallery);
// assign id to end of route
return inertia('backend/cms-gallery-edit', ['data' => $data]);
}
Or, you can customize it using parameter method. Refer to here
Route::resource('/admin/gallery', GalleryController::class)->only('edit')->parameters([
'gallery' => 'id'
]);
And your controller
public function edit($id)
{
$data = Gallery::find($id);
// assign id to end of route
return inertia('backend/cms-gallery-edit', ['data' => $data]);
}

Laravel Route Redirect with URL Parameter

I am trying to generate a unique id and then redirect to a different route with id in the url parameter. But I am getting error as :
"Route [sequences] not defined."
Here is my route defined:
Route::get('/sequences_create','SequencesController#create');
Route::get('/sequences/{id}', 'SequencesController#show');
Here is the create function on the sequences controller:
public function create()
{
$uniq = 'seq'. uniqid();
$seq = new Sequences;
$seq->id = $uniq;
$seq->user_id = auth()->user()->id;
$seq->name = 'New Sequence'; //temp name
$seq->save();
return redirect()->route('sequences', ['id' => $uniq]);
}
you have not set a name for your route by name() method.
try it:
Route::get('/sequences_create','SequencesController#create')->name('sequances.create');
Route::get('/sequences/{id}', 'SequencesController#show')->name('sequances.show');
then:
public function create()
{
//...
return redirect()->route('sequences.show', ['id' => $uniq]);
}
you need to name your route.
Route::get('/sequences_create','SequencesController#create')->name('sequences.create');
Route::get('/sequences/{id}', 'SequencesController#show')->name('sequences.show');
Then change your redirect to:
return redirect()->route('sequences.show', ['id' => $uniq]);

laravel multiple parameter pass throught controller and show database first result

how i show my index title and body from index table
this is my route which i have 2 parameter
Route::get('forum/{forumthread}/{forumindex}', [
'uses' => 'ForumController#indexshow',
'as' => 'forum.index.show'
]);
here is my controller
public function indexshow($slug){
$forumindex = forumindex::where('slug', $slug)->first();
$forumthread = forumthread::where('slug', $slug)->first();
return view('forum.index.index', compact('forumthread', 'forumindex', ''));
}
here is my view
{{ $forumthread->thread }} // this is working
{{ $forumindex->title }} //this is not working
help me to sort out this method thank you
You need to specify all the parameters in your indexshow method,
Try this:
public function indexshow($head_slug, $index_slug){
$forumindex = forumindex::where('slug', $index_slug)->first();
$forumthread = forumthread::where('slug', $head_slug)->first();
return view('forum.index.index', compact('forumthread', 'forumindex', ''));
}

Pass fixed variable from route to controller in Laravel

I'm trying to pass a variable through my route to my controller, but I have multiple routes (categories) leading to the same controller i.e.
Route::get('/category1/{region}/{suburb?}', 'SearchController#search');
Route::get('/category2/{region}/{suburb?}', 'SearchController#search');
Making /category1, 2, etc. to be a parameter /{category} is not an option and I don't want to make separate controller function for each category.
How do I send the first segment of the url to my search controller? i.e. category1 or category2?
At present controller is as follows:
public function search($region, $suburb = null) { }
Thanks!
You can specify a mask for your {category} parameter so that it must fit the format "category[0-9]+" in order to match the route.
Route::get('/{category}/{region}/{suburb?}', 'SearchController#search')
->where('category', 'category[0-9]+');
Now, your example url (from the comments) www.a.com/var1/var2/var3 will only match the route if var1 matches the given category regex.
More information can be found in the documentation for route parameters here.
Edit
Yes, this can work with an array of string values. It is a regex, so you just need to put your array of string values into that context:
Route::get('/{category}/{region}/{suburb?}', 'SearchController#search')
->where('category', 'hairdresser|cooper|fletcher');
Or, if you have the array built somewhere else:
$arr = ['hairdresser', 'cooper', 'fletcher'];
// run each array entry through preg_quote and then glue
// the resulting array together with pipes
Route::get('/{category}/{region}/{suburb?}', 'SearchController#search')
->where('category', implode('|', array_map('preg_quote', $arr)));
Edit 2 (solutions for original request)
Your original question was how to pass the hardcoded category segment into the controller. If, for some reason, you didn't wish to use the solution above, you have two other options.
Option 1: don't pass the value in, just access the segments of the request in the controller.
public function search($region, $suburb = null) {
$category = \Request::segment(1);
dd($category);
}
Option 2: modify the route parameters using a before filter (L4) or before middleware (L5).
Before filters (and middleware) have access to the route object, and can use the methods on the route object to modify the route parameters. These route parameters are eventually passed into the controller action. The route parameters are stored as an associative array, so that needs to be kept in mind when trying to get the order correct.
If using Laravel 4, you'd need a before filter. Define the routes to use the before filter and pass in the hardcoded value to be added onto the parameters.
Route::get('/hairdresser/{region}/{suburb?}', ['before' => 'shiftParameter:hairdresser', 'uses' => 'SearchController#search']);
Route::get('/cooper/{region}/{suburb?}', ['before' => 'shiftParameter:cooper', 'uses' => 'SearchController#search']);
Route::get('/fletcher/{region}/{suburb?}', ['before' => 'shiftParameter:fletcher', 'uses' => 'SearchController#search']);
Route::filter('shiftParameter', function ($route, $request, $value) {
// save off the current route parameters
$parameters = $route->parameters();
// unset the current route parameters
foreach($parameters as $name => $parameter) {
$route->forgetParameter($name);
}
// union the new parameters and the old parameters
$parameters = ['customParameter0' => $value] + $parameters;
// loop through the new set of parameters to add them to the route
foreach($parameters as $name => $parameter) {
$route->setParameter($name, $parameter);
}
});
If using Laravel 5, you'd need to define a new before middleware. Add the new class to the app/Http/Middleware directory and register it in the $routeMiddleware variable in app/Http/Kernel.php. The logic is basically the same, with an extra hoop to go through in order to pass parameters to the middleware.
// the 'parameters' key is a custom key we're using to pass the data to the middleware
Route::get('/hairdresser/{region}/{suburb?}', ['middleware' => 'shiftParameter', 'parameters' => ['hairdresser'], 'uses' => 'SearchController#search']);
Route::get('/cooper/{region}/{suburb?}', ['middleware' => 'shiftParameter', 'parameters' => ['cooper'], 'uses' => 'SearchController#search']);
Route::get('/fletcher/{region}/{suburb?}', ['middleware' => 'shiftParameter', 'parameters' => ['fletcher'], 'uses' => 'SearchController#search']);
// middleware class to go in app/Http/Middleware
// generate with "php artisan make:middleware" statement and copy logic below
class ShiftParameterMiddleware {
public function handle($request, Closure $next) {
// get the route from the request
$route = $request->route();
// save off the current route parameters
$parameters = $route->parameters();
// unset the current route parameters
foreach ($parameters as $name => $parameter) {
$route->forgetParameter($name);
}
// build the new parameters to shift onto the array
// from the data passed to the middleware
$newParameters = [];
foreach ($this->getParameters($request) as $key => $value) {
$newParameters['customParameter' . $key] = $value;
}
// union the new parameters and the old parameters
$parameters = $newParameters + $parameters;
// loop through the new set of parameters to add them to the route
foreach ($parameters as $name => $parameter) {
$route->setParameter($name, $parameter);
}
return $next($request);
}
/**
* Method to get the data from the custom 'parameters' key added
* on the route definition.
*/
protected function getParameters($request) {
$actions = $request->route()->getAction();
return $actions['parameters'];
}
}
Now, with the filter (or middleware) setup and in use, the category will be passed into the controller method as the first parameter.
public function search($category, $region, $suburb = null) {
dd($category);
}

Pass get parameter to controler in Laravel

How do I pass a get variable to a controller in Laravel?
I have:
$languages = array('zh');
$locale = Request::segment(1);
if (in_array($locale, $languages)) {
App::setLocale($locale);
} else {
$locale = null;
}
Route::group(array('prefix' => $locale), function() {
...
Route::get('/search/{q}', array('as' => 'search', 'uses' => 'ProductsController#index'));
...
});
If I try to return q from within the controller using Input::get('q'); I get nothing.
Route::get('/search/{q}', array('as' => 'search', 'uses' => 'ProductsController#index'));
the {q} here isn't GET variable.
you can take the value like this.
public function index($q)
{
echo $q;
}
It's not a GET parameter but an URL parameter. There's a little difference in that.
Url paramters will be passed (in the order they appear) to the controller action.
So all you have to do, is use the argument that gets automatically passed to the function in the controller.
public function index($q){
echo $q;
}

Categories