Customizing URLs with prefix in laravel

泄露秘密 提交于 2019-12-13 16:15:35

问题


I have this html:

<ul>
   <li><a href="index.php/Page1">Page 01</a></   
   <li><a href="index.php/Page2">Page 02</a></li>
   <li><a href="index.php/Page3">Page 03</a></li>
</ul>  

As you can see, I need to use the index.php/prefix in all links due to the server of my university
(I can't change it). The way is done above, it works fine to go straightfoward from home to any page, but if I try to access a page from another page, I get a wrong URL and Can't access the page:

Examples:

Home
http://localhost/php-project/public/

Page1 (From home)
FROM: http://localhost/php-project/public/
TO: http://localhost/php-project/public/index.php/Page1

Page2 (From home)
FROM: http://localhost/php-project/public/
TO: http://localhost/php-project/public/index.php/Page2

Page1 (From Page2)
FROM: http://localhost/php-project/public/index.php/Page2
TO: http://localhost/php-project/public/index.php/index.php/Page1

as you can see, the prefix repeats itself. I have no idea how to do it to work right.

Any ideas?


回答1:


You can set it using the method forceRootUrl on the class Illuminate\Routing\UrlGenerator.

Example:

// app/Providers/AppServiceProvider
public function boot()
{
    // Instance of Illuminate\Routing\UrlGenerator
    $urlGenerator = $this->app['url'];

    // Instance of Illuminate\Http\Request
    $request = $this->app['request'];

    // Grabbing the root url
    $root = $request->root();

    // Add the suffix
    $rootSuffix = '/index.php';
    if (!ends_with($root, $rootSuffix)) {
        $root .= $rootSuffix;
    }

    // Finally set the root url on the UrlGenerator
    $urlGenerator->forceRootUrl($root);
}



回答2:


You can use the Route prefix.

Route::group(['prefix'=>'/index.php/'], function()
{
    Route::get('/', ['as'=>home, 'uses'=>'HomeController@index']);
    //Include all your routes here. And in your view, link any page with the route name. 
    // eg: <a href="{{URL::route('home')}}"></a>
});



回答3:


This is how I solved my problem:

  • I created a helper function on laravel's helper.php

function custom_url($routename) { return str_replace("index.php", "",URL($routename)); }

And used like this:

<ul>
     <li><a href="{{custom_url('index.php/Page1')}}">Importar Histórico</a></li>
     <li><a href="{{custom_url('index.php/Page2')}}">Alocar Disciplina</a></li>    
</ul>


来源:https://stackoverflow.com/questions/35234328/customizing-urls-with-prefix-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!