我是Laravel的新人。我想问一下,如何在控制器中找到一个slu ?? 例如,我的网址是www.example.com/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
}
}
答案 0 :(得分:0)
您可以使用action()
辅助函数来获取指向给定控制器和放大器的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);
答案 1 :(得分: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"
}
}
但是要小心你宣布路线的顺序很重要。因此,您必须在通用&#34; catch-all&#34;之前声明所有其他路线。最后的路线。
答案 2 :(得分:0)
不应为每个页面/ slug声明多个路由,而应该使用route参数声明一个路由,例如:
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
路由,那么home
也将类似于带有slug的动态路由( {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