简体   繁体   中英

Setting Routes Dynamically in Laravel 5.4

I'm brand new to Laravel, and I'm tinkering with it in different ways to understand how it works.

One of the first things that I've tried is to create routes dynamically by creating a routes config file that is essentially an array of views, and loop through them to create the route. It looks like this:

 // Loop through the routes foreach( config("routes.web") as $route ){ $GLOBALS["tmp_route"] = $route; // set the path for home $path = ($route == "home" ? '/' : $route); Route::get( $path, function() { return view($GLOBALS["tmp_route"]); }); // foreach } 

I know the loop is working fine, but what I get is 'Undefined index: tmp_route' .

I'm confused as to why this isn't working? Any ideas? If I echo out the tmp_route it echos out the value, but fails at the return view(.

We don't use loops in routes usually. Actually, I've never used a loop in routes if I remember correctly. My suggestion is create a route with paramater and assign it to a controller method. eg:

// Note that if you want a route like this, just with one parameter,
// put it to end of your other routes, otherwise it can catch other
// single hard-coded routes like Route::get('contact')
Route::get('{slug}')->uses('PageController@show')->name('pages.show');

Then in your PageController

public function show($slug) {

    $view = $slug == '/'?'home':$slug;
    return view($view);        

}

With this, http://example.com/my-page will render views/my-page.blade.php view. As you can see I also gave him a name, pages.show . You can use route helper to create links with this helper. eg

echo route('pages.show','about-us'); // http://example.com/about-us
echo route('pages.show','contact'); // http://example.com/contact

In blade templates:

<a href="{{ route('pages.show','about-us') }}">About Us</a>

Please look at the documentation for more and other cool stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM