rewriting the URLs dynamically laravel - laravel

I am trying to rewrite some of the pages URL in my web app, for example, I have a company details page and I want the URL of this page to contain the name of the company without space or special characters and to have the id too, and I have no idea on how to do that or where to start.
I tried adding the name of the company in the route as a parameter like this:
Route::get('/{RS}-{id}', 'App\Http\Controllers\SiteController#getDetails')->name('details');
It didn't work for some reason and even if it worked there's no way to replace the special characters with their normal form and replace the space with dashes.
This the URL I'm getting: http://mywebsite.come/entreprise_details-13109
this the URL I want: http://mywebsite.come/yoorika-managements-13109 ( with Yoorika Managements being the name of the company )
I searched a lot but I can't seem to find what I am looking for, I just need someone to help me find the right term. thank you!

In route :
Route::get('/{input}', 'App\Http\Controllers\SiteController#getDetails')->name('details');
In controller :
public function getDetails($input)
{
$input_array = explode("-", $input);
$name = $input_array[0];
$id = $input_array[1];
$data = MyModel::where('id', $id)->get();
// return data to view
}
In list view, you may display data like this (table cell ) :
<td> <a href="/{{name .'-'.{{id}}"> {{name .'-'.{{id}}<td/>

Related

show name instead of id in a url using laravel routing

I have defined a route in laravel 4 that looks like so :
Route::get('/books/{id}', 'HomeController#showBook');
in the url It shows /books/1 for example , now i'm asking is there a way to show the name of the book instead but to keep also the id as a parameter in the route for SEO purposes
thanks in advance
You could also do something like this:
Route::get('books/{name}', function($name){
$url = explode("-", $name);
$id = $url[0];
return "Book #$id";
});
So you can get book by id if you pass an url like: http://website.url/books/1-book-name
if your using laravel 8, this may be helpfull.
In your Controller add this
public function show(Blog $blog)
{
return view('dashboard.Blog.show',compact('blog'));
}
In your web.php add this
Route::get('blog/{blog}', [\App\Http\Controllers\BlogController::class,'show'])->name('show');
Then add this to your model (am using Blog as my Model)
public function getRouteKeyName()
{
return 'title'; // db column name you would like to appear in the url.
}
Note: Please let your column name be unique(good practice).
Result: http://127.0.0.1:8000/blog/HelloWorld .....url for a single blog
So no more http://127.0.0.1:8000/blog/1
You are welcome.
You can add as many parameters to the url as you like, like this:
Route::get('/books/{id}/{name}', 'HomeController#showBook');
Now when you want to create an url to this page you can do the following:
URL::action('HomeController#showBook', ['id' => 1, 'name' => 'My awesome book']);
Update:
If you are certain that there will never be two books with the same title, you can just use the name of the book in the url. You just need to do this:
Route::get('/books/{name}', 'HomeControllers#showBook');
In your showBook function you need to get the book from the database using the name instead of the id. I do strongly encourage to use both the id and the name though because otherwise you can get in trouble because I don't think the book name will always be unique.
You can also use model binding check more on laravel docs
For example
Route::get('book/{book:name}',[BookController::class,'getBook'])->name('book');
The name attribute in "book/{book:name}" should be unique.

MVC URL issues (Codeigniter)

I'm building a website using Codeigniter and I really like how in the MVC pattern URLs are used to reference controller methods. It seems very logical and intuitive however, I seem to be running in an array of issues with this very pattern!
So I am building an events website and currently I'm passing everything through one main Site controller, passing a number of parameters:
public function index($page = NULL, $city = NULL, $type_venue = NULL, $slug = NULL)
{
// if the page argument is empty show the homepage
if( ! ($page))
{
$page = 'home';
}
// create an array for passing to the views
$data = array(
'title_city' => $city,
'title_type_venue' => str_replace('-', ' ', $type_venue),
'locations' => $this->locations_model->load(),
'events' => $this->events_model->load($city, $type_venue, $slug),
'venues' => $this->venues_model->load($city, $slug)
);
// construct the page layout with the following views
$this->load->view('partials/head', $data);
$this->load->view('partials/header', $data);
$this->load->view('content/'.$page, $data);
$this->load->view('partials/footer');
}
This works fine, in that it loads content for the following URLs:
site.com/events/bristol/open-mic/city-varieties/another-incredible-event
site.com/events/bristol/open-mic/city-varieties/
site.com/events/bristol/open-mic/
site.com/events/bristol/
However if I want to pass anything else through this controller that isn't an event, i.e. register/user, I have to write a specific route for this!
Worth noting my routing is:
$route['(:any)'] = 'site/index/$1';
I could write separate controllers for each entity, i.e. events, venues, cities but each one would look largely like the above (correct?) in that each would need the parameters to get the data.
My question is - what is the best practice approach for developing long query strings like this? Is a single controller correct? It doesn't feel like it, but then multiple controllers would violate DRY, just because they all need so much similar data. Any help appreciated!
Avoid putting everything into a single controller; even further, in each controller, avoid putting everything into a single index function.
There is no need to write specific controllers for each function in Codeigniter - suggest you read that part again in the manual. Most of your routing will be done automatically for you if you follow the normal guidelines.
The more you try to use a single controller or function, the more you will have to add untestable, unmanageable, unscalable conditional code later.

Country name in codeigniter url

My question is how to append country name in codeigniter url?
Lets say my website is http://mywebsite.com and I am opening the website from Canada so my url should be http://mywebsite.com/canada.
Meaning I just want to append the country name in the url, nothing change except this. I have read about routes of codeigniter, I have googled it but all in vain.
If anyone have a clue how to do this please let me know.
I guess you'd do that with a IP lookup to guess the country based on the request IP address ($_SERVER['REMOTE_ADDR']). Mapping the IP address to a location is pretty well documented. Once you have the country, redirect to the correct controller method.
That what you're looking for?
This is like for language code in url.
With my solution you can put any segment in your uri and hide it to CI.
http://site.com/page.html will be equal to http://site.com/canada/page.html and vice versa.
set_country_uri.php
//App location
$ci_directory = '/ci/';
//countries
$countries = array('canada','france');
//default country
$country = 'canada';
foreach( $countries as $c )
{
if(strpos($_SERVER['REQUEST_URI'], $ci_directory.$c)===0)
{
//Store country founded
$country = $c;
//Delete country from URI, codeigniter will don't know is exists !
$_SERVER['REQUEST_URI'] = substr_replace($_SERVER['REQUEST_URI'], '', strpos($_SERVER['REQUEST_URI'], '/'.$c)+1, strlen($c)+1);
break;
}
}
//Add the country in URI, for site_url() function
$assign_to_config['index_page'] = $country."/";
//store country founded, to be able access it in your app
define('COUNTRY', $country);
index.php
<?php
require('set_country_uri.php');
//ci code ...
So in your CI code use COUNTRY constant to know wich is used. And make your code like routing without take in consideration the country in the uri.

CodeIgniter - Dynamic URL segments

I was wondering if someone could help me out.
Im building a forum into my codeigniter application and im having a little trouble figuring out how i build the segments.
As per the CI userguide the uri is built as follows
www.application.com/CLASS/METHOD/ARGUMENTS
This is fine except i need to structure that part a bit different.
In my forum i have categories and posts, so to view a category the following url is used
www.application.com/forums
This is fine as its the class name, but i want to have the next segment dynamic, for instance if i have a category called 'mycategory' and a post by the name of 'this-is-my-first-post', then the structure SHOULD be
www.application.com/forums/mycategory/this-is-my-first-post
I cant seem to achieve that because as per the documentation the 'mycategory' needs to be a method, even if i was to do something like /forums/category/mycategory/this-is-my-first-post it still gets confusing.
If anyone has ever done something like this before, could they shed a little light on it for me please, im quite stuck on this.
Cheers,
Nothing is confusing in the document but you are a little bit confused. Let me give you some suggestions.
You create a view where you create hyperlinks to be clicked and in the hyperlink you provide this instruction
First Post
In the controller you can easily get this
$category = $this->uri->segment(3);
$post = $this->uri->segment(4);
And now you can proceed.
If you think your requirements are something else you can use a hack i have created a method for this which dynamically assign segments.
Go to system/core/uri.php and add this method
function assing_segment($n,$num)
{
$this->segments[$n] = $num;
return $this->segments[$n];
}
How to use
$this->uri->assign_segment(3,'mycategory');
$this->uri->assign_segment(4,'this-is-my-first-post');
And if you have error 'The uri you submitted has disallowed characters' then go to application/config/config.php and add - to this
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
You could make a route that forwards to a lookup function.
For example in your routes.php add a line something like;
$route['product/(:any)/(:any)'] = "forums/cat_lookup/$1/$2";
This function would then do a database lookup to find the category.
...
public function cat_lookup($cat, $post) {
$catid = $this->forum_model->get_by_name($cat);
if ($catid == FALSE) {
redirect('/home');
}
$post_id = $this->post_model->get_by_name($post);
/* whatever else you want */
// then call the function you want or load the view
$this->load->view('show_post');
}
...
This method will keep the url looking as you want and handle any problems if the category does not exist.Don't forget you can store the category/posts in your database using underscores and use the uri_title() function to make them pretty,
Set in within config/routes.php
$route['song-album/(:any)/:num'] = 'Home/song_album/$id';
fetch in function with help of uri segment.
$this->uri->segment(1);

filter a string to remove disallowed characters to compose an URL in CodeIgniter

I'm trying to make URL-friendly links for the blog on my portfolio.
So I would like to obtain links something like site/journal/post/{title}
Obviously Journal is my controller, but let's say my title would be 'mysite.com goes live!' I would like to have a valid url like site/journal/post/mysitecom-goes-live where all disallowed characters are removed.
How would I transform 'mysite.com goes live!' to 'site/journal/post/mysitecom-goes-live' in CodeIgniter based on the characters in $config['permitted_uri_chars']
use the url helper
$this->load->helper('url');
$blog_slug = url_title('Mysite.com Goes live!');
echo $blog_slug //mysitecom-site-goes-live
// might differ slightly, but it'll do what you want.
to generate url-friendly links.
Store this value in a field in your blog table (url_title/url_slug) whatever.
make a function:
class Journal extends controller
{
//make your index/constructor etc
function view($post)
{
$this->blog_model->get_post($post);
// etc - your model returns the correct post,
// then process that data and pass it to your view
}
}
your blog_model has a method get_post that uses CI's
$this->db->where('url_title', $post);
hope that makes sense.
then when you access the page:
site.com/journal/view/mysite-goes-live
the function will pick up "mysite-goes-live" and pass it to the view() function, which in turn looks up the appropriate blog entry in the database.

Resources