Have a dynamic optional route parameter in index - php

I use :
Route::controller('home', 'HomeController');
in my routes to link all routes to my controller.
I have a getIndex() function in my controller that's executed when I go to '/home'.
I have a case where I'd like to route to '/home/slug', but not always.
I tried using getIndex($slug), but it always asks for '/home/index/{slug?}'. I don't want index to appear.

Not possible using implicit controllers, as far as the documentation goes (as it seems to enforce RESTFUL pattern).
But your can create a new route just for that:
Route::get('home/{slug}','HomeController#slugedIndex');
Route::controller('home', 'HomeController');
Edit: as pointed by Steve the controller method must come after the get method so one does not overwrite the other.

Arthur's answer was :
Route::get('home/{slug}','HomeController#slugedIndex');
Route::controller('home', 'HomeController');
Although it doesn't work, because anything written after 'home/' will now go into the first route (and HomeController#slugedIndex).
I found a workaround though. I took out the route in routes.php :
Route::controller('home', 'HomeController');
Then in my HomeController, I used the missingmethod() that's called whenever a method isn't found in the controller.
Here's the missing method :
public function missingMethod($parameters = array())
{
$sSlug = is_string($parameters) ? $parameters : '';
$oObject = Object::where('slug', $sSlug)->first();
if ($oObject) {
// slug code
}
else {
// 404 code
}
}

Related

Is it possible to use dynamic controller name in routing in CodeIgniter 4?

I want to use route localization like said here https://codeigniter.com/user_guide/outgoing/localization.html#in-routes
So I need to add route rule like:
$routes->get('{locale}/books', 'App\Books::index');
But I want to make this rule for all controllers - not to specify rules for all controllers. So I added the rule:
$routes->add('{locale}/(:segment)(:any)', '$1::$2');
I have controller Login with method index(). When I go to mydomain.com/Login method index() is loaded successfull. But when I go to mydomain.com/en/Login (as I expect to use my route) I got 404 Error with message - "Controller or its method is not found: \App\Controllers$1::index". But locale is defined and set correctly.
If I change my route to $routes->add('{locale}/(:segment)(:any)', 'Login::$2'); then mydomain.com/en/Login is loaded successfull as I want. But in this way I have to set routes for every controller and I want to set one route to work with all controllers.
Is it possible to set route with setting of dynamic controller name?
I'm not sure it is possible directly, but here is a workaround:
$routes->add('{locale}/(:segment)/(:any)', 'Rerouter::reroute/$1/$2');
Then, your Rerouter classlooks like this:
<?php namespace App\Controllers;
class Rerouter extends BaseController
{
public function reroute($controllerName, ...$data)
{
$className = str_replace('-', '', ucwords($controllerName)); // This changes 'some-controller' into 'SomeController'.
$controller = new $className();
if (0 == count($data))
{
return $controller->index(); // replace with your default method
}
$method = array_shift($data);
return $controller->{$method}(...$data);
}
}
For example, /en/user/show/john-doe will call the controller User::show('john-doe').

Controller Method not found in nesting laravel 4

I'm new in laravel and I got an error and don't really know how to fix it.
I got an error "Controller method not found" when i'm asking for this route : /projet/6/note
My routes.php
Route::controller('projet.note', 'NoteController');
Route::resource('/eleves', 'StudentController');
Route::controller('/auth', 'AuthController');
Route::resource('/user', 'UserController');
Route::resource('/projet', 'ProjectController');
Route::post('/eleves/search', 'StudentController#postSearch');
Route::resource('/classe', 'ClasseController');
Route::controller('/', 'HomeController');
I tried to type php artisan routes to see if the routes was working, and she's not.
I tried then to change controller into resource in the line about NoteController, the routes was there but when i go on the link, same error.
Then i guess i can't do 'projet/note' without that my NoteController is a resource?
It's a problem because i need to nest NoteController to ProjetController.
My only action in NoteController
public function getIndex($id)
{
return View::make('note.noter')
->with('project', Project::find($id))
;
}
Thanks
I hope I understood your question right. This is the best solution I could come up with:
Route::any('projet/{id}/note/{action?}', function($id, $action = 'index'){
$controller = App::make('NoteController');
$action = strtolower($_SERVER['REQUEST_METHOD']).studly_case($action);
if(method_exists($controller, $action)){
return $controller->callAction($action, [$id]);
}
});
This basically does some similar things as Route::controller. First we create a controller instance, then build the action name out of the request method and the second parameter in the route and in the end, call the action (if it exists).

How to route cutom URL with to custom controller in CodeIgniter?

I have a PHP CodeIgniter Controller with name User and have a method that get details of user user_detail($username)
Now when i need to show user data for example for userName mike
I call this URL
http://www.example.com/user/user_detail/mike
My target
How to make user data accessible by next URLs
http://www.example.com/user/mike
or / and
http://www.example.com/mike
You have to read the this page from the official documentation of codeigniter. It covers all related things to Routing URLs easily. All routes must be configured via the file:
application/config/routes.php
It could be something like this :
$route['user/(:any)'] = "user/user_detail/$1";
This can be achieved by overriding CI_Controller class BUT dont change the original core files, like I said override the controller and put your logic in it.
Help: https://ellislab.com/codeigniter/user-guide/general/core_classes.html
how to create Codeigniter route that doesn't override the other controller routes?
Perhaps an easier solution would be to route it with the help of apache mod_rewrite in .htaccess
Here is an detailed explanation on how to achieve it: http://www.web-and-development.com/codeigniter-remove-index-php-minimize-url/
Hatem's answer (using the route config) is easier and cleaner, but pointing the usage of the _remap() function maybe helpful in some cases:
inside the CI_Controller, the _remap() function will be executed on each call to the controller to decide which method to use. and there you can check if the method exist, or use some defined method. in your case:
application/controllers/User.php
class User extends CI_Controller {
public function _remap($method, $params = array())
{
if (method_exists(__CLASS__, $method)) {
$this->$method($params);
} else {
array_unshift($params, $method);
$this->user_detail($params);
}
}
public function user_detail($params) {
$username = $params[0];
echo 'username: ' . $username;
}
public function another_func() {
echo "another function body!";
}
}
this will result:
http://www.example.com/user/user_detail/john => 'username: john'
http://www.example.com/user/mike ........... => 'username: mike'
http://www.example.com/user/another_func ... => 'another function body!'
but it's not going to work with: http://www.example.com/mike , since the controller -even if it's the default controller- is not called at all, in this case, CI default behaviour is to look for a controller called mike and if it's not found it will throws 404 error.
for more:
Codeigniter userguide 3: Controllers: Remapping Method Calls
Redirect to default method if CodeIgniter method doesn't exists.

Laravel get route name from given URL

In Laravel, we can get route name from current URL via this:
Route::currentRouteName()
But, how can we get the route name from a specific given URL?
Thank you.
A very easy way to do it Laravel 5.2
app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1'))->getName()
It outputs my Route name like this slug.posts.show
Update: For method like POST, PUT or DELETE you can do like this
app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1', 'POST'))->getName()//reference https://github.com/symfony/http-foundation/blob/master/Request.php#L309
Also when you run app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1', 'POST')) this will return Illuminate\Routing\Route instance where you can call multiple useful public methods like getAction, getValidators etc. Check the source https://github.com/illuminate/routing/blob/master/Route.php for more details.
None of the solutions above worked for me.
This is the correct way to match a route with the URI:
$url = 'url-to-match/some-parameter';
$route = collect(\Route::getRoutes())->first(function($route) use($url){
return $route->matches(request()->create($url));
});
The other solutions perform bindings to the container and can screw up your routes...
I don't think this can be done with out-of-the-box Laravel. Also remember that not all routes in Laravel are named, so you probably want to retrieve the route object, not the route name.
One possible solution would be to extend the default \Iluminate\Routing\Router class and add a public method to your custom class that uses the protected Router::findRoute(Request $request) method.
A simplified example:
class MyRouter extends \Illuminate\Routing\Router {
public function resolveRouteFromUrl($url) {
return $this->findRoute(\Illuminate\Http\Request::create($url));
}
}
This should return the route that matches the URL you specified, but I haven't actually tested this.
Note that if you want this new custom router to replace the built-in one, you will likely have to also create a new ServiceProvider to register your new class into the IoC container instead of the default one.
You could adapt the ServiceProvider in the code below to your needs:
https://github.com/jasonlewis/enhanced-router
Otherwise if you just want to manually instantiate your custom router in your code as needed, you'd have to do something like:
$myRouter = new MyRouter(new \Illuminate\Events\Dispatcher());
$route = $myRouter->resolveRouteFromUrl('/your/url/here');
It can be done without extending the default \Iluminate\Routing\Router class.
Route::dispatchToRoute(Request::create('/your/url/here'));
$route = Route::currentRouteName();
If you call Route::currentRouteName() after dispatchToRoute call, it will return current route name of dispatched request.

Get controller action from url, laravel

Can I get the controller action from given URL?
In my project, I will have different layout used for admin and normal users. i.e.
something.com/content/list - will show layout 1.
something.com/admin/content/list - will show layout 2.
(But these need to be generated by the same controller)
I have added filter to detect the pattern 'admin/*' for this purpose. Now I need to call the action required by the rest of the URL ('content/list' or anything that will appear there). Meaning, there could be anything after admin/ it could be foo/1/edit (in which case foo controller should be called) or it could be bar/1/edit (in which case bar controller should be called). That is why the controller name should be generated dynamically from the url that the filter captures,
So, I want to get the controller action from the URL (content/list) and then call that controller action from inside the filter.
Can this be done?
Thanks to everyone who participated.
I just found the solution to my problem in another thread. HERE
This is what I did.
if(Request::is('admin/*')) {
$my_route = str_replace(URL::to('admin'),"",Request::url());
$request = Request::create($my_route);
return Route::dispatch($request)->getContent();
}
I could not find these methods in the documentation. So I hope, this will help others too.
You can use Request::segment(index) to get part/segment of the url
// http://www.somedomain.com/somecontroller/someaction/param1/param2
$controller = Request::segment(1); // somecontroller
$action = Request::segment(2); // someaction
$param1 = Request::segment(3); // param1
$param2 = Request::segment(3); // param2
Use this in your controller function -
if (Request::is('admin/*'))
{
//layout for admin (layout 2)
}else{
//normal layout (layout 1)
}
You can use RESTful Controller
Route:controller('/', 'Namespace\yourController');
But the method have to be prefixed by HTTP verb and I am not sure whether it can contain more url segment, in your case, I suggest just use:
Route::group(array('prefix' => 'admin'), function()
{
//map certain path to certain controller, and just throw 404 if no matching route
//it's good practice
Route::('content/list', 'yourController#yourMethod');
});

Categories