Pagination Conundrum - codeigniter

I used Codeigniter to build my site, and everything is going peachy, except when it comes to dealing with pagination. Because database queries are driven by data passed from my URL, this is screwing everything up. I'm SURE I'm overlooking something obvious, but this is my issue:
/events/town/venue/event-name
All fine and works as expected; the method takes the parameters from the URL to get the data and deliver it. But my question is - what do I do when I want to paginate my Events page? I.e.
/events/2
/events/3
...etc
As far as my controller, and my routes are concerned, the page number here is considered a town, which it isn't. How do I get around this?
Many thanks

"Test" your town or "page number" uri segment, if it is integer then
you sure know that you are looking for pagination thing, otherwise
"normal" behavior of your controller/method pattern.
using PHPs is_numeric.
A little pseudo code:
if (is_numeric($this->uri->segment(n))) {
//pagination stuff
} else {
//regular behavior
}
In case you are using aplication/config/routes.php consider using _remap() instead (for this certain controller).
or use routes as following:
$route['events/(:num)'] = "events/page/$1"; //pagination "behind the scene" with method "page" (that is not seen by user).
$route['events/town/venue/(:any)'] = "events/town/venue/$1";

Related

How to differentiate between two dynamic url in Laravel

I have two dynamic url with simillar structure. For example, lets say, Product page and category page.
I have set both pages in
Route::get('/{product}', [UsersController:: class, 'productDetail']);
Route::get('/{category}', [UsersController:: class, 'categoryProducts']);
But when I click on url which suppose to go in category page, it redirect to product page only because of same structure. How I can differentiate both URLs for Laravel without altering their url structure?
I don't think this can be done without modifying the URL pattern at least a little bit.
If you do something like /50?type=category then in the show method you can use the query parameter to determine which table to look at. But you'll have to use the same show method and I don't recommend doing it this way.
I hope someone else will be able to shine some more light on the matter.
this is the best practice for your case to make yourapi Resful
Route::get('/product/{product-id}', [UsersController:: class, 'productDetail']);
Route::get('/product/categories, [UsersController:: class, 'categoryProducts']);
learn more about Restful api here https://restfulapi.net/resource-naming/
This should be done by calling index, update diff() function. You can try by using the below:
Route::get('/category/{slug}', 'site\categorycontroller#show')->name('category.show');
Route::get('/product/{slug}', 'site\productcontroller#show')->name('product.show');

MVC Routing Engine routes same formatted route to different controller actions

Okay, I did my homework and search SO, and indeed I found similar questions but not reporting the behavior I'm getting.
Here is the deal, I have defined a route:
routes.MapRoute("CategoryName", "Category/Name/{text}",
new { controller = "Category", action = "Name", text = "" });
The twist here is the following:
This url: http://www.url.com/Category/Name/existingCategoryName
And this url: http://www.url.com/Category/Name/anotherExistingCategoryName
Both url's should go to the same controller method which is public ActionResult Name(string text) but sadly the first url is going to the default Index method, the second is being routed correctly.
I wonder why this happens, as I've been with .net mvc for several years and never experienced this behavior.
As a side note here are some facts:
As it's being route to different methods, I doubt the code inside them has something to do with it.
When manually write the category to something it doesn't exists in the DB as a category name it goes through the Name method.
The routes are placed correctly, as I'm aware the first route that matches the pattern will win.
Even I tried place the CategoryName route first, the behavior is the same.
When writing each link in the Category/Index I use the same #Html.RouteLink() helper, so all the links are formatted the same way.
Thanks in advance!
Are you using the - sign in the failing route?
Maybe you can find more information with the Routing debugger
And maybe you can look at this question: Failing ASP.NET MVC route. Is this a bug or corner case?
Phil Haack also give an possible answer to your problem in: ASP.NET routing: Literal sub-segment between tokens, and route values with a character from the literal sub-segment

Passing multiple values as query string is good or bad practice in MVC

In my page I ve to pass multiple values to controller.
My URL looks something like :
http://blah/Search/Page/?type=new&keywords=blahblah&sortType=Date
Is Passing multiple values as query string good practice in MVC ? or We can have slash separated URL, by using introducing custom routing?
NB: Lets consider all the values in my query string, are not secure / sensitive data.
I wouldn't consider it a bad practice, as long as it's not senstive data. It just depends if you want to write a custom route in your global.asax to handle it or not. The custom routes provide a cleaner url forsure. Also, for more savy users if they understand the concept on your site, it's more intuitive.
So consider this:
http://baseballcards/topps/1980 // search for baseball cards made by topps in the 1980s
http://recipes/deserts/pies // search for a desert recipe that are pies
http://code/csharpe/linq // search for csharp code that has linq examples
In these examples we can almost read the url like a sentence, making it more intuitive, giving a user the ability to plug and play. It clearly denotes the query almost like a breadcrumb, indicating exactly what the context will be. I personally like this. But either way is a good approach.
To extend with more parameters:
routes.MapRoute(
"SearchRecipes",
"Search/Recipes/{category}/{type}",
new { controller = "Search", action = "Recipes", category = "all" , type = ""}
);
Some examples:
Search/Recipes/Deserts/Pie
Search/Recipes/Dinner/Beef
Search/Recipes/Lunch/Salads
Select later (query string in route values) in case,
If you are concerned about header length.( By default get parameters are part of headers, and web server accept 1024 byte header length by default in IIS7).
Hide logical implementation of your code.
Url looks good and easier to remember.
Otherwise Both the approaches work equally.
I think passing search parameters in the query string is the way you should go, especially if all your parameters are optional. It also enables you to use normal method="get" forms without hassle.
I don't think "security/personal data" has anything to do with this since the query string is a part of the URL just like the path is.
IMO I think this is absolutely fine. I think it is actually preferable to use querystrings in MVC when the path represents the function and the querystring parameters represent the filters, e.g. as in a search.
However, I wouldn't use querystring parameters for data that represent information about the content retrieved. So I would include the year and month of an article in the path but not the page number if returning more than one page of articles for the year and month.

Change CodeIgniter route for static pages and auth login [duplicate]

I have a problem with Codeigniter routes. I would like to all registered users on my site gets its own "directory", for example: www.example.com/username1, www.example.com/username2. This "directory" should map to the controller "polica", method "ogled", parameter "username1".
If I do like this, then each controller is mapped to this route: "polica/ogled/parameter". It's not OK:
$route["(:any)"] = "polica/ogled/$1";
This works, but I have always manually entered info in routes.php:
$route["username1"] = "polica/ogled/username1";
How do I do so that this will be automated?
UPDATE:
For example, I have controller with name ads. For example, if you go to www.example.com/ads/
there will be listed ads. If you are go to www.example.com/username1 there are listed ads by user username1. There is also controller user, profile, latest,...
My Current routes.php:
$route['oglasi'] = 'oglasi';
$route['(:any)'] = "polica/ogled/$1"
$route['default_controller'] = 'domov';
$route['404_override'] = '';
I solved problem with this code:
$route['oglasi/(:any)'] = 'oglasi/$1';
$route['(:any)'] = "polica/ogled/$1"
$route['default_controller'] = 'domov';
$route['404_override'] = '';
Regards, Mario
The problem with your route is that by using :any you match, actually...ANY route, so you're pretty much stuck there.
I think you might have two solutions:
1)You can selectively re-route all your sites controller individually, like:
$route['aboutus'] = "aboutus";
$route['where-we-are'] = "whereweare";
//And do this for all your site's controllers
//Finally:
$route['(:any)'] = "polica/ogled/$1";
All these routes must come BEFORE the ANY, since they are read in the order they are presented, and if you place the :any at the beginning it will happily skip all the rest.
EDIT after comment:
What I mean is, if you're going to match against ANY segment, this means that you cannot use any controller at all (which is, by default, the first URI segment), since the router will always re-route you using your defined law.
In order to allow CI to execute other controllers (whatever they are, I just used some common web pages, but can be literally everything), you need to allow them by excluding them from the re-routing. And you can achieve this by placing them before your ANY rule, so that everytime CI passed through your routing rules it parses first the one you "escaped", and ONLY if they don't match anything it found on the URL, it passes on to the :ANY rule.
I know that this is a code verbosity nonetheless, but they'll surely be less than 6K as you said.
Since I don't know the actual structure of your URLs and of your web application, it's the only solution that comes to my mind. If you provide further information, such as how are shaped the regular urls of your app, then I can update my answer
/end edit
This is not much a pratical solution, because it will require a lot of code, but if you want a design like that it's the only way that comes to my mind.
Also, consider you can use regexes as the $route index, but I don't think it can work here, as your usernames are unlikely matchable in this fashion, but I just wanted to point out the possibility.
OR
2) You can change your design pattern slightly, and assign another route to usernames, something along the line of
$route['user/(:any)'] = "polica/ogled/$1";
This will generate quite pretty (and semantic) URLs nonetheless, and will avoid all the hassle of escaping the other routes.
view this:
http://www.web-and-development.com/codeigniter-minimize-url-and-remove-index-php/
which includes remove index.php/remove 1st url segment/remove 2st url sigment/routing automatically.it will very helpful for you.
I was struggling with this same problem very recently. I created something that worked for me this way:
Define a "redirect" controller with a remap method. This will allow you to gather the requests sent to the contoller with any proceeding variable string into one function. So if a request is made to http://yoursite/jeff/ or http://yoursite/jamie it won't hit those methods but instead hit http://yoursite/ remap function. (even if those methods/names don't exist and even if you have an index function, it supersedes it). In the _Remap method you could define a conditional switch which then works with the rest of your code re-directing the user any way you want.
You should then define this re-direct controller as the default one and set up your routes like so:
$route['(.*)'] = "redirect/index/$1";
$route['default_controller'] = "redirect";
This is at first a bit of a problem because this will basically force everything to be re-directed to this controller no matter what and ultimately through this _remap switch.
But what you could do is define the rules/routes that you don't want to abide to this condition above those route statements.
i.e
$route['myroute'] = "myroute";
$route['(.*)'] = "redirect/index/$1";
$route['default_controller'] = "redirect";
I found that this produces a nice system where I can have as many variable users as are defined where I'm able to redirect them easily based on what they stand for through one controller.
Another way would be declaring an array with your intenal controllers and redirect everything else to the user controller like this in your routes.php file from codeigniter:
$controllers=array('admin', 'user', 'blog', 'api');
if(array_search($this->uri->segment(1), $controllers)){
$route['.*'] = "polica/ogled/$1";
}

Using and hiding default class

This is my first time getting my hands dirty with CI so I'm getting a little confused.
I'm wanting to accomplish a couple things with my question. First of all, I'd like to always use the default controller without having it to appear in the url. For example, I created a new class named after my site (Example.php) and that works fine. However, if I want to call the search function in my controller I then have to go to example.com/index.php/example/search/.
The second thing I want to accomplish is when I run a search I'll get a nice looking url like so: example.com/search/This+is+a+search (I haven't gotten to removing the index.php portion but I know to use a htaccess). I'm not worried about the actual mechanics of the search, just that I'd like to format the url in this way.
I originally experimented with using a Search class but that found that it doesn't allow me put the search in the url because the second parameter should be a function and not the extra stuff.
Thanks for any help.
In application/config/routes.php file add $route to redirect everything to your controller.
Something like this:
$route['([^\/]+)'] = 'content/index/$1';
$route['([^\/]+)\/([^\/]+)'] = 'content/index/$1/$2';
This will redirect urls like example.com/A and example.com/A/B to a controller named content. Parameters A and B will be passed to method index.

Resources