I'm new in Yii2 so I have Brands table with their types ('brand', 'author', 'company')
and their slug name so I need the URL like that www.site.com/{brand_type}/{brand_slug}
without controller name so how to do that ?
Asked
Active
Viewed 722 times
0

Nurjan
- 5,889
- 5
- 34
- 54

Mohamed Gamal
- 35
- 5
1 Answers
0
This is commonly called pretty URLs. To do achieve that in Yii2 put this in your app config file under 'components'
key
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
// ...
'<type:\w+>/slug:\w+>' => 'yourcontroller/youraction',
// ...
],
],
The result is that when you passed a URL in the format you specified, your controller will $type
and $slug
as parameters you can use in your controller which is expected to take the form:
class YourcontrollerController extends YourBaseController
{
...
public function actionYouraction($type, $slug)
{
// Do whatever you want with these variables
}
...
}
Notice that you will need your web server to configure executing your app's index.php
even if it is not in the URL. For Apache this can be done, for example, using .httaccess (More details here) :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
The Definitive Guide to Yii 2.0 has an excellent section about this topic
-
As per your answer, we need to add rule for each slug? – Manikandan S Oct 12 '16 at 16:58
-
No, the `$slug ` variable as well as the `$type` variable will be available to the controller to do whatever you want – mmonem Oct 12 '16 at 17:11
-
Thanks for reply. sorry it is confusing for me. If you don't mind can you update your answer with controller method please. – Manikandan S Oct 12 '16 at 17:14
-
Updated the answer – mmonem Oct 12 '16 at 17:53
-
Thanks for updating your answer. For example in my table I have multiple brands like Apple, Micorsoft, Google etc. So for each brands I have to create separate methods, Am I correct? – Manikandan S Oct 12 '16 at 17:56
-
No, the brand is passed to you, exactly the type and slug in the question – mmonem Oct 12 '16 at 19:31
-
Thanks a lot. I hope I understood. I have to try. anyway thanks :) – Manikandan S Oct 12 '16 at 19:48