Add prefix to all routes, links and urls - laravel-4

Is it possible to add some prefix to all routes, urls and links in the whole application at one place including blades?
For example I have route
Route::get('/', 'HomeController#showWelcome');
but instead of it I want to have
Route::get($prefix . '/', 'HomeController#showWelcome');
and in blade
{{ HTML::style('css/bootstrap.min.css') }}
to
{{ HTML::style($prefix . 'css/bootstrap.min.css') }}
I tried
Route::group(array('prefix' => $prefix), function() {});
but it did not apply prefix to links in blades.

I found simple solution. I created .env.php folder inside project which looks like
return array(
'ROUTES_PREFIX' => 'prefix',
);
then added this code to all routes
Route::group(array('prefix' => $_ENV['ROUTES_PREFIX']), function() {
// routes here
});
and created custom macro for style, script and image. For example my macro for style looks like this
HTML::macro('extendedStyle', function($url, $attributes = array(), $secure = null) {
$prefix = $_ENV['ROUTES_PREFIX'] == '' ? '' : $_ENV['ROUTES_PREFIX'] . '/';
return HTML::style($prefix . $url, $attributes, $secure);
});
I hope, someone will find this useful.

Related

Laravel route with multiple names

Cant i have two names with one route?
Something like below:
Route::get('/', 'Admin\HomeController#index')->name(['admin.home', 'planner.home.index']);
Thanks!
This works only if you need the name, not the URL, although it's tricky and sloppy.
Route::get('/', 'Admin\HomeController#index')->name('admin.home');
Route::get('/2', function() {
return redirect()->route('admin.home')
})->name('planner.home.index');
So if you use route('admin.home') or route('planner.home.index') it will redirects you to the method index in your HomeController.
You can make this, if you seek to have 2 version(route name) in the same app.
<?php
$routes = ['v1' => 'app.name1.', 'v2' => 'app.name2.'];
foreach ($routes as $routeVersion => $routeName) {
// Yours router app (i.e app/v1/pages or app/v2/pages)
// Your router name (i.e app.name1 or app.name2)
Route::prefix('app' . $routeVersion)
->middleware('auth')
->name($routeName)
->group(function(){
# Your custom routes
...
}
}
}
?>
This is an example of the response in the route list
I hope it serves you!
foreach($pages as $key => $page){
Route::any("/".$page, "Controller#index")->name($page);
}

How to add dynamically prefix to routes?

In session i set default language code for example de. And now i want that in link i have something like this: www.something.com/de/something.
Problem is that i cant access session in routes. Any suggestion how can i do this?
$langs = Languages::getLangCode();
if (in_array($lang, $langs)) {
Session::put('locale', $lang);
return redirect::back();
}
return;
Route::get('blog/articles', 'StandardUser\UserBlogController#AllArticles');
So i need to pass to route as prefix this locale session.
If you want to generate a link to your routes with the code of the current language, then you need to create routes group with a dynamic prefix like this:
Example in Laravel 5.7:
Route::prefix(app()->getLocale())->group(function () {
Route::get('/', function () {
return route('index');
})->name('index');
Route::get('/post/{id}', function ($id) {
return route('post', ['id' => $id]);
})->name('post');
});
When you use named routes, URLs to route with current language code will be automatically generated.
Example links:
http://website.com/en/
http://website.com/en/post/16
Note: Instead of laravel app()->getLocale() method you can use your own Languages::getLangCode() method.
If you have more questions about this topic then let me know about it.
Maybe
Route::group([
'prefix' => Languages::getLangCode()
], function () {
Route::get('/', ['as' => 'main', 'uses' => 'IndexController#index']);
});

route() helper function in a different locale

I'm trying to create a language switcher, so that you can easily change language on the fly (without being redirected to the home page).
The thing I can't seem to accomplish is getting a url from a route name in a different locale.
Imagine your on mydomain.com/events (or mydomain.com/en/events since these are the same) and I want to get url in french (mydomain.com/fr/evenements)...
In my routes.php I have:
$locale = Request::segment(1);
if ( !array_key_exists($locale, Config::get('translatable.languages'))) {
$locale = null;
App::setlocale(Config::get('translatable.fallback_locale'));
}else{
App::setLocale($locale);
}
Route::group(array('prefix' => $locale), function(){
Route::get(Lang::get('routes.events'), array('as' => 'events.index', 'uses' => 'EventController#index'));
});
I have tried
setting the application locale right before calling the route($route_name) helper function
Setting a session variable with the requested locale (in this example 'fr'), then calling the route($route_name) function. For this I also added at the top of routes.php:
if( Session::has('requested_locale') ){
$locale = Session::pull('requested_locale');
}
I have no idea's left on how to handle this...
I know there is a package Laravel Localization that can do this, but I need it to work without that package (if possible)...
My solution on Laravel 5.1 was...
Defined locales in the config/app.php to create routes using the language files
'locale' => 'en',
'locales' => [
'en'=>'English',
'fr'=>'Français'
],
I've defined my routes in the resources/lang/ directory ('en/routes.php' and 'fr/routes.php' in my case)
return [
'about' => 'a-propos',
];
Defined routes using the language keys, example:
Route::get(trans('routes.about'), ['as' => 'about', function () {
return view('pages.'.App::getLocale().'.about');
}]);
Then I've created dummy route that would be used only for switching to another locale, ONLY after the current route has been matched to request
`
Route::matched(function($route) {
$route = Route::current();
$route_name = $route->getName();
$route_uri = $route->uri();
$locales = Config::get('app.locales');
foreach ($locales as $locale_code => $locale_name) {
if ($locale_code == App::getLocale()) {
continue;
}
if (Lang::has('routes.'.$route_name, $locale_code)) {
$route_uri = $locale_code . '/' . Lang::get('routes.'.$route_name, [], $locale_code);
}
else {
$route_uri = $locale_code . '/' . substr($route_uri, 3);
}
Route::get($route_uri, ['as' => 'change_locale_to_'.$locale_code, function(){
}]);
}
});
`
Finally, I use the dummy route in the view I want. $locale_toggle is a Locale eloquent Model that I'm setting in a Middleware for handling the language with a language code route prefix.
<a href="{{ route('change_locale_to_'.$locale_toggle->code, Route::current()->parameters()) }}" class="dropdown-toggle">

Multiple routes defaults to controller in Laravel

I want to be able to get to an article by a short-link, like this articles/ID, but I also want to get there with the full link articles/ID/category/slug. But I can not get the following to work:
// Route file:
Route::pattern('id', '[0-9]+');
Route::pattern('cat', '^(?!create).*');
Route::pattern('slug', '^(?!edit).*');
Route::get('articles/{id}/{cat?}/{slug?}', ['as' => 'articles.show', 'uses' => 'ArticlesController#show']);
// Controller file:
public function show($id, $cat = null, $slug = null)
{
dd('1: ' . $cat . ' | 2:' . $slug);
}
The following link articles/28/ullam/vel-repellendus-aut-est-est-esse-fugiat gives the result:
string(53) "1: ullam/vel-repellendus-aut-est-est-esse-fugiat | 2:"
I don't understand why it's not split, if I remove the ? in my route definition it works.
I have tried this solution https://stackoverflow.com/a/21865488/3903565 and that works, but not when directed at a controller. Why?
Update; I ended up rearranging my routes file:
Route::pattern('id', '[0-9]+');
// Articles
Route::get('articles/create', ['as' => 'articles.create', 'uses' => 'ArticlesController#create']);
Route::get('articles/edit/{id}', ['as' => 'articles.edit', 'uses' => 'ArticlesController#edit']);
Route::get('articles/{id}/{category?}/{slug?}', ['as' => 'articles.show', 'uses' => 'ArticlesController#show']);
Route::get('articles/{category?}', ['as' => 'articles.index', 'uses' => 'ArticlesController#index']);
Route::resource('articles', 'ArticlesController', ['only' => ['store', 'update', 'destroy']]);
Is that your only route? Or you have a different one pointing to show too? I just added this one as my first route:
Route::get('articles/{id}/{cat?}/{slug?}', function($id, $cat, $slug)
{
dd($id.': ' . $cat . ' | 2:' . $slug);
});
And got this result:
28: ullam | 2:vel-repellendus-aut-est-est-esse-fugiat
Change the order of your routes to have the first one as your most specific routes and the last as your most generic one. Also, if you have any patterns, they can be inteferring with your results.
Looks like there's a problem with some patterns and optional parameters (?), so if you do
Route::pattern('id', '[0-9]+');
Route::pattern('cat', '^(?!create).*');
Route::pattern('slug', '^(?!edit).*');
Route::get('articles/{id}/{cat}/{slug}', function($id, $cat, $slug)
{
dd($id.': ' . $cat . ' | 2:' . $slug);
});
It will work fine. My advice is to not reuse routes too much, if you have an specific route, you create a route command for it and add it before your most generic ones:
Route::get('articles/{id}/create', function($id)
{
dd('this is the create route');
});
Route::get('articles/{id}/{cat}/{slug}', function($id, $cat, $slug)
{
dd($id.': ' . $cat . ' | 2:' . $slug);
});
The cost of creating new routes is low in comparison to the complexity of looking to regex patterns and try to find your way amongst them. Having new collaborators on projects, or even for your future self, the simpler, the better.
In Laravel 4.3 you'll have access to route caching, which makes routes being fired almost instantly.
The problem is only in the lookahead patterns.
You need $ and class excluding / in order to make it work.
So here they are:
Route::pattern('id', '[0-9]+');
Route::pattern('cat', '^(?!create$)[^/]*');
Route::pattern('slug', '^(?!edit$)[^/]*');
Route::get('articles/{id}/{cat?}/{slug?}', function($id, $cat, $slug)
{
dd($id.': ' . $cat . ' | 2:' . $slug);
});

Laravel 4 - Deleting a record from the database

Once again, i am stumped.
I have a table of letters, each with the following link attached
Delete {{ $letter->lettername }}
From the docs i can see i have to run the following from my routes.php
$letter = Letter::find(1);
$letter->delete();
My question is, what do i have to enter in the href to pass the letters ID onto the routes file, and then how do i pass that to the find() parameter?
Do i do something like this
Delete {{ $letter->lettername }}
If so, how do i put that ID into the find paramter.
Im confused.
Any help would be greatly appreciated
Cheers
My Routes file is as follows:
Route::get('letters', array(
'before' => 'auth|userdetail',
function()
{
// Grab the letters, if any, for this user
$letters = Letters::forUser(Auth::user())->get();
$data = [
'letters' => $letters
];
return View::make('letters', $data);
}
));
You could do it like this
Delete {{ $letter->lettername }}
But it would be better if you have a named route
Delete {{ $letter->lettername }}
Then in your routes
Route::get('letters/delete/{id}', array('as' => 'letters.delete', 'before' => 'auth|userdetail', function($id)
{
echo ("You want to delete letter id: " . $id . " from the system");
// Put your delete code here
}

Resources