如何获得一个slu to控制器?

问题描述 投票:0回答:3

我是Laravel的新手。我想问一下,如何在控制器中找到一个slu ??例如,我的网址是www.example.com/contact-us

我需要在控制器中的变量中获得“contact-us”值。有什么简单的方法吗?

在另一个网址上,例如www.example.com/faq我需要在同一个变量中使用值“faq”。我该怎么做?非常感谢

使用laravel 5.5

这是我的路线文件中的内容:

Route::get('/home', 'HomeController@index')->name('home');
Route::get('/podmienky-pouzitia', 'StaticController@index');
Route::get('/faq', 'StaticController@index');
Route::get('/o-projekte', 'StaticController@index');

这是我的StaticController文件中的内容:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\StaticModel;

class StaticController extends Controller
{
    public function index($slug) {
        var_dump($slug); // I need to get a variable with value of my actual slug
    }
}
php laravel-5
3个回答
0
投票

您可以将静态页面slug设为参数:

Route::get('/home', 'HomeController@index')->name('home');
Route::get('/{slug}', 'StaticController@index'); //This replaces all the individual routes

在静态控制器中:

 public class StaticController extends Controller {
     public function index($slug) {
          // if the page was /faq then $slug = "faq"              
     }
 }

但是要小心你宣布路线的顺序很重要。因此,您必须在结尾处的一般“全包”路线之前声明所有其他路线。


0
投票

您应该只使用route参数声明一条路由,而不是为每个页面/ slug声明多个路由,例如:

Route::get('/{slug}', 'StaticController@index');

在这种情况下,index方法将在slug参数中接收$slug,例如:

public function index($slug)
{
    var_dump($slug);
}

现在,您可以使用以下内容发出请求:

http://example.com/faq // for faq page
http://example.com/contact-us // for contact page

所以,$slug现在将包含faq/contact-us等等。但是,在这种情况下,你会遇到问题,例如,http://exampe.com/home也会类似于带有slug的动态路径,所以,如果你在动态路线之前声明home路线(一个用{slug}),那么StaticController@index将被调用,所以要么,您在父命名空间下使用slug声明动态路由,例如:

Route::get('/static/{slug}', 'StaticController@index');

因此,您可以轻松区分路径或使用slug参数声明动态路径,并在路径声明中添加where约束(如果您有一些具有这些slugs的预定义静态页面)。 Here is a somewhat similar answer,可能会有所帮助。另外,请查看有关route constraints的更多信息。

更新:您还可以使用以下内容添加路径约束:

Route::get('/{slug}', 'StaticController@index')->where('slug', 'faq|contact|something');

以上声明仅匹配以下网址:

http://example.com/faq
http://example.com/contact
http://example.com/something

0
投票

您可以使用action()辅助函数来获取指向给定Controller和Method的URL。

routes.php文件:

Route::get('/home', 'HomeController@index')->name('home');

HomeController.php:

class HomeController extends Controller {
    public function index (Request $request) {
        $url = action('HomeController@index');
        // $url === 'http://www.example.com/home'

        // OR

        $path = $request->path();
        // $path === 'home';
    }
}

如果您使用第一种方式,则可以使用request()帮助程序(或Request实例)从字符串中删除域:

$url = str_replace(request()->root(), '', $url);
© www.soinside.com 2019 - 2024. All rights reserved.