Route every request to a given controller unless another controller is specified - php

I'm trying to achieve the following behavior: http://example.com/anything should pass anything to a default controller (namely, "category_browser"), unless anything is a controller name.
The first part is easily achieved with this line in config/routes.php:
$route[':any'] = "category_browser";
while I did not manage to get the second one to work.
I would really appreciate any input.
Other info: the number of controllers is pretty small; writing an options line for each of them is an option; they should be passed parameters.

Use this:
http://pinoytech.org/blog/post/CodeIgniter-Route-Everything-except-these-Controllers
$route['^(?!controller|controller|controller)\S*'] = "article/$1";

create a master controller that you point everything to. in the master controller, check if the set controller name exists, if so, run it, if not, call category_browser using controller name as method instead.

Related

Laravel : form does not change the URL after submit, causing me to be unable to do another POST in web.php

I have a bit of a complicated issue. I could use some help.
I have a form that is being handled by the following function:
$module = request('module');
$classe = request('classe');
$horaire = request('horaire');
$date = request('date');
$students = DB::select('SELECT * FROM `etudiants` WHERE etudiants.id_classe = '.$classe);
return view('g_absence.absence',['module'=> $module, 'classe'=>$classe,'horaire'=>$horaire,'date'=>$date,'students'=>$students]);
I take the values $module, $class, $horaire, $date and $students and need to use them inside a different view: g_absence.absence. This works fine and when the view is returned I have access to said variables.
The issue is, inside the g_absence.absence view, I have another form that also needs to be handled, and because the url remains the same even tho a different view is returned, I cant make two posts for the same path.
web.php:
Route::get('/testboy', [App\Http\Controllers\g_absence::class,'index'])->name('marquer');
Route::post('/testboy',[App\Http\Controllers\g_absence::class, 'marquer']);
Route::post('/testboy',[App\Http\Controllers\g_absence::class, 'ajoutabsence']);
The first line is the one that send to the form page just a simple
return view
The second one handle the form in that view
The third one, I want it to handle the form inside the
g_absence.absence view, but they share the same path.
Excuse me if I'm being unclear, I'm a bit of a beginner in Laravel
your problem is using the same route for different methods
basically the first route gets executed every time you use the '/testboy' action that is why your second function never get's called.
you can solve this issue by changing your urls for example:
Route::post('/testboy-marquer',[App\Http\Controllers\g_absence::class, 'marquer']);
Route::post('/testboy-ajoutabsence',[App\Http\Controllers\g_absence::class, 'ajoutabsence']);
Or you can use one function that's handle both with one url by pathing additional parameter to your url depending on your function call :
Route::post('/testboy?type=marquer',[App\Http\Controllers\g_absence::class, 'ajoutabsence']);
in your function check the type :
if(request('type') == 'marquer') {
execute marquer logic here...
} else {
execute absence logic here...
}
Using method and path with two functionalities is wrong, but if you want to somehow use both routes my same method and path which I don't recommend you must let the request to pass through like a middleware in your first block of code Instead of return a view.
Recommended way is to have 2 routes with different paths or at least one route with a parameter by which you can determine what code block must be executed.

It is possible to pass 2 differents types of parameters to a Laravel controller?

I already have a GET route with an URI /projects/{id} which displays Infos of a project with a given id. I also have a GET index route (/projects), which shows all my projects.
My problem is that I currently try to create different indexes (for example one which only displays the projects where I am assigned [e.g. on /projects/mines], or the projects which are pending administrator approval [e.g. on /projects/proposals], and still others displays).
So I want to know if I can have two GET routes /projects/{id}and /projects/{display_mode} which will be calling two differents methods of my ProjectController (respectively show and index).
Thanks for your help! :)
You may have one route /projects which returns all projects as default.
If there is query parameter like
/projects?displayMode=proposals
then you can apply filters.
In your controller it would look something like this
$projects = Project::query();
if ($request->query('displayMode') == 'proposals')
$projects->where('pending', true)
return $projects->get();
You can add multiple filters too in the same way
I'm not sure about specific Laravel options for the route definitions (sorry!), but if the {id} will always be an integer and {display_mode} will always have non-digits in it, you could keep just one route, but do the conditional handling in your controller. Just have the mainAction do something likeā€¦
return preg_match('/^\d+$/', $param) ? idHelperAction($param) : displayModeHelperAction($param);
Then create those two helper functions and have them return whatever you want.
$param is supposed to be whatever you get from that route parameter -- /projects/{param}.
That should call the idHelperAction for routes where $param is all digits and nothing else; otherwise, it should call the displayModeHelperAction. Either way, it sends the same $param to the helper function and returns whatever that helper function returns -- effectively splitting one route definition into two possible actions.
Of course, you might have to add some context in the code sample. If the functions are all defined in the same class, you might need to use $this->idHelperAction($param) or self::idHelperAction($param) (and the same with the other helper action), depending on whether it's static or not; or tell it where to find the functions if you put them in another class, etc., etc. -- all the normal contextual requirements.

Codeigniter complex wildcard Routing

Hi guys I am trying to achieve something that I hope is possible but couldn't find the right way to find.
I am using codeigniter 2.2.0
I want to use an url in codeigniter like
domain/username/controller/method/$args
Let me explain When user types an url like
domain/mike/job/editJob/12/urgent/
Here "mike" is someone's user name
"job" will be a controller alias
"editJob" will be a method
"12" and "urgent" will be parameter of editJob method.
editJob method will have three parameters.
I want "mike" as 1st parameter,
then "12" and "urgent" as second and third parameter.
So far what I have done in my routes
$route['(:any)/job/(:any)'] = 'job_c/$2/$1';
When I type in the url
domain/mike/job/editJob/12/urgent
in Job controller I get
"12" as first parameter
"urgent" as second parameter
and "mike" as third parameter
**
Is there any possible way to get "mike" as first parameter and then the rest is okay**
Edited:
One more thing if I pass three parameters after method then I am not
getting the username!!
I need to have the username as first parameter because there may have multiple parameters in any method and there is a possibility to have conditional parameters as well.
One more thing I want to know. Is it possible to make such route that will work the same as my given route but the controller alias will also be wildcard. Or if there is any way to check if a segment in url is a controller then one route and if not a controller then something else should happen.
I am not a well describer still tried to keep it simple. If anyone knows something that will help me a lot.
Thanks
UPDATE
Is there any way to keep the username "mike" in session from routes.php file thus I don't have to pass this as a parameter.
Updating Again
I have solved the issue somehow.
I am using
$route['(:any)/garage/([^/]*)/([^/]*)/(.*)'] = '$2/$3/$1/$4';
Here garage is nothing but a simple identifier for the route. This route will work when it gets garage as a second segment in url. It will work like
domain/user/garage/anyControler/anyMethod/manyParameters
It's completely dynamic only the garage is used as identifier. If you want you can use your controller name instead of using any identifier. then you don't have to declare same thing multiple times for multiple controllers but it will work fine. It will work for any controller and any method. In addition it supports dynamic number of parameters.
I don't know if there is any better way to do this but it solves my issue. If anyone know something better then this then please share.
I think what is happening is that you are accessing
domain/mike/job/editJob/12/urgent
and its being parsed like:
job_c/editJob/12/urgent/mike
Because:
$route['(:any)/job/(:any)'] = 'job_c/$2/$1';
$2 = (:any)/job/(:any) = editJob/12/urgent
$1 = (:any)/job/(:any) = mike
Substituting:
job_c/editJob/12/urgent/mike
You could try to keep your route as similar as your current one:
$route['(:any)/job/(:any)/(:any)'] = 'job_c/$2/$1/$3';
This will allow you to match $2 to any method name, and have $1 as the first parameter and $3 as the rest of params.
But, I would suggest, if this is a very specific route, substituting the $2 :any, with the actual method name and the expected type of the params, otherwise, you might receive unexpected values to every method in the matching controller.
I would use something like:
$route['(:any)/job/editJob/(:num)/(:any)'] = 'job_c/editJob/$1/$2/$3';
Hope this helps.
Update:
For the controller matching: Code Igniter uses the form controller/method/param1/param2/...
As long as you create routes that matches controllers, methods and params in that order, you can do anything.
$route['(:any)/(:any)/(:any)'] = '$1/$2/$3';
or just
$route['(:any)'] = '$1';
and hopefully it will contain a controller and method and the required params.
I think this will totally be missing the point of having a routing system.

How to access values of multiple parameters passed to Laravel controller

I am trying to figure out how to access two (or more) parameters passed to a Laravel controller. I know how to create the route, and the URL is created correctly, but then I can only access the first passed parameter in my controller.
Route:
Route::get('managers/{id}/{parameter2}', array('as'=>'dosomething', 'uses'=> 'ManagersController#dosomething'));
where the first parameter is obviously the $id for managers, and the second parameters is to be processed by the controller.
View:
Do Something
generates the URL:
http://domain/managers/1/2
where 1 is easily accessed as the $id for managers, but when I try to access the 2nd parameter "2" using $parameter2, e.g. using a simple return: "id=$id and parameter2=$parameter2" statement, I get an "unidentified variable: $parameter2" error.
What am I doing wrong?
Is there a better way to pass multiple parameters? I'm especially asking the "better way?" question because what I want to do is use the 2nd parameter to change a value in a database table, and using a 'get' method, somebody could change the parameter value in the URL and therefore cause mischief. Must I use a 'post' method? I'd love to be able to use a link, since that works much better with the design of my application.
Thanks!
I was asked to include the controller, which I'm happy to do. Initially, just for testing, as I mentioned, my controller was a simple return to display the values of the two passed parameters. But here is what I want to be able to do, including the actual name of the function ("update_group" rather than "dosomething") --
ManagersController:
public function update_group($id)
{
DB::table('groups')->where('id','=',$parameter2)->update(array('manager_id'=>$id));
return Redirect::route('managers.show', array('id'=>$id));
}
The update table works perfectly if I replace $parameter2 with an actual value, so that syntax is fine. The issue is that Laravel says that $parameter2 is an undefined variable, despite the fact that the URL contains the value of $parameter2 as you can see above.
And since it occurs to me that the answer to this may involve adding a function to the Manager model, here is the current
Manager.php
class Manager extends Eloquent {
protected $table = 'managers'; ... (mutator and error functions)
}
Just change
public function update_group($id)
to
public function update_group($id, $parameter2)
All looks ok in your route. Seeing the controller code would help, but likely, you may not have a second parameter in your controller's dosomething() method.
public function dosomething($id, $parameter2){
var_dump($id).'<br />';
var_dump($paremter2);
}
If that isn't the case, you can try dumping it from the route's callback to further diagnose.
Route::get('managers/{id}/{parameter2}', function($id, $parameter2)
{
var_dump($id).'<br />';
var_dump($paremter2);
});
Depending on your use case, you can pass them in a query string like so: but it isn't really the 'best way', unless you're doing something like building an API that won't use the same variables in the same order all the time.
/managers?id=1&paramter2=secondParameter
var_dump(Request::query('id')).'<br />';
var_dump(Request::query('paramter2'));

How can I change Zend Framework's routing schema to not use key/value pairs?

Rather than using controller/action/key1/value1/key2/value2 as my URL, I'd like to use controller/action/value1/value2. I think I could do this by defining a custom route in my Bootstrap class, but I want my entire application to behave this way, so adding a custom route for each action is out of the question.
Is this possible? If so, how would I then access valueN? I'd like to be able to define the parameters in my action method's signature. e.x.:
// PostsController.php
public function view($postID) {
echo 'post ID: ' . $postID;
}
I'm using Zend Framework 1.9.3
Thanks!
While I don't think it's possible with the current router to allow N values (a fixed number would work) you could write a custom router that would do it for you.
I would question this approach, however, and suggest that actually listing all of your routes won't take long and will be easier in the long run. A route designed as you've suggested would mean that either your named parameters are always in the same order, i.e.
/controller/action/id/title/colour
or that they are almost anonymous
/controller/action/value1/value2/value3
With code like
$this->getRequest()->getParam('value2'); //fairly meaningless
Does it have to be N or can you say some finite value? For instance can you imagine that you'll never need more than say 5 params? If so you can set up a route:
/:controller/:action/:param0/:param1/:param2/:param3/:param4
Which will work even if you don't specify all 5 params for every action. If you ever need 6 somewhere else you can just add another /:paramN onto the route.
Another solution I've worked with before is to write a plugin which parses the REQUEST_URI and puts all the extra params in the request object in the dispatchLoopStartup() method. I like the first method better as it makes it more obvious where the params are coming from.

Categories