Muhammad Atallah
Muhammad Atallah

Reputation: 976

Dynamic url segment name in laravel 5.1

In fact i'm looking for way to fetch url segment and replace it to another string name for example /setting show it in my view الضبط in Arabic

After research i found substr_replace or str_ireplacecan achieve that as the following:

  $seg2 = request()->segment(2);

 ($seg2 == 'setting') ? $seg2 = str_ireplace($seg2,'الضبط',$seg2) : $seg2 = str_ireplace($seg2,'another_segment_name', $seg2);

I see this approach is very bad if i have many of different routes can to be in $seg2 place .

If there any other way can achieve that please help me ,Thanks

Upvotes: 1

Views: 894

Answers (2)

Muhammad Atallah
Muhammad Atallah

Reputation: 976

Thanks @The Alpha for your help in fact i have been achieved my needs now but i did some changes to achieve it i will show it for help any somebody else needs to do that

at first i created segments.php file in resources/lang/ar and change local language to ar in config/app.php

and in segments.php

<?php

// Segments Array for navigation paths on view  

return [
  'users' => 'المستخدمين',  //maybe to be seg2
  'settings' => 'الضبط',   //also maybe to be seg2
];

and in my view

<!-- Simple condition to check if user on segment 2 or not and fetch the proper segment name according to incoming segment in url -->
            {{(request()->segment(2) != '') ? trans('segments.'.request()->segment(2)) : '' }}

Upvotes: 0

The Alpha
The Alpha

Reputation: 146191

In my opinion you can use a localized file, what I mean hera that, you may use Laravel's Localization feature. For example, put a messages.php file in resources/lang/ar folder and can map key => value pairs like:

<?php

return [
    'settings' => 'الضبط',
    'otherKey' => 'some Arabic word'
];

Then, you may use it like the following (it'll replace the settings with appropriate value):

echo trans('messages.' . request()->segment(2));

// Or use this for blade template
{{ trans('messages.' . request()->segment(2)) }}

To make it working you need to set locale (default language) to ar in config/app.php file but you may automize it, I mean, you can set the locale at the runtime. Hope You got the idea, just read the documentation properly. By the way, this is only an idea, you may do it differently if necessary.

Upvotes: 1

Related Questions