lararel课堂:理解laravel的路由参数

今天,我们一起来看看laravel的路由特性。此时,我们将演练学习laravel如何操作路由参数,并且体验一下稍微高级和复杂一些的场景。

今天,我们一起来看看laravel的路由特性。此时,我们将演练学习laravel如何操作路由参数,并且体验一下稍微高级和复杂一些的场景。

路由参数(Route Parameters)

Laravel允许我们在路由中使用路由参数,这在我们想要创建类似子分类或特殊的识别参数(例如name,id,或其他参数)的时候会有很大帮助,让我们一起看看使用路由参数的不同方式。

 

获取一个基本的路由参数

在此案例中,我们有一个为users准备的路由,并且我们拉取识别参数。我们将用通过name和id两种不同方式来演示。



	// get the cuteness level of a puppy
	Route::get('puppies/{cutelevel}', function($cutelevel) 
	{
		return 'This puppy is an absolute ' . $cutelevel . ' out of ' . $cutelevel;
	});

	// OR

	// get the parameter of name
	Route::get('users/{name}', function($name) 
	{
		return 'User Name is ' . $name;
	});

测试 Cuteness Level: 在浏览器打开http://example.com/puppies/5, 浏览器上会显示 This puppy is an absolute 5 out of 5.

测试Name: 在浏览器打开 http://example.com/users/chris, 浏览器上会显示 User Name is Chris.

使用可选的路由参数

 

此案例中,我们有一个相册的照片,我们也有两个分类的照片,这个分类是可选的,否则我们将只显示全部照片。



	// optional category
	Route::get('gallery/{category?}', function($category) 
	{
		// if category is set, show the category
		// if not, then show all
		if ($category)
			return 'This is the ' . $category . ' section.';
		else 
			return 'These are all the photos.';

	});

测试可选分类: 访问 http://example.com/gallery/puppies,浏览器会显示 This is the puppies section.

测试无可选分类: I访问http://example.com/gallery, 浏览器会显示 These are all the photos.

路由参数默认的情况

我们希望一个用户有一个自己选择的分类。所以,如果没有一个被选择的分类,将自动匹配给我sunsets分类。



	// optional category with a default
	Route::get('gallery/{category?}', function($category = 'sunsets')
	{
		return 'This is the ' . $category . ' category.';
	});

测试无分类:访问 http://example.com/gallery,浏览器显示:This is the sunsets category.

测试有分类:访问http://example.com/gallery/puppies, 浏览器显示: This is the puppies category.

拉取真实的数据

我们练习了一些基本路由参数之后,让我们探讨一下在真实场景中的应用吧。我们就用相册的例子。

在真实世界,你不能让给你的访客一个只告诉他们正在puppies分类的场景,你的用户想看puppies分类的照片。

如果你已经安装好了laravel应用、迁移、数据库,让我们用Eloquent 来根据路由参数拉取数据.

Once you also have your Eloquent model, you can call the information you need from the route (of course when your application gets larger, you’ll want to move this logic into a controller).

一旦你有你的Eloquent模型,你就能从路由调用信息(当然,当你的应用变大的时候,你将会想移动此逻辑到controller里).



	// get the category of gallery for viewing
	Route::get('gallery/{category?}', function($category) {

		// get the gallery stuff for the category
		$gallery = Gallery::where('category', '=', $category);

		// return a view and send the gallery data to the view
		return View::make('gallery')
			->with('gallery', $gallery);
	});

结论

就像你看到的,使用路由参数和Eloquent ORM 来拉取真实数据,并且发送到你的view视图里,这其实很简单。

如果你在开发一些复杂的应用,出现一些问题,可以通过评论提问. 你可以参考路由过滤 filters 手册,这里有 认证,路由组等更强大的功能.

最后,推荐阅读官方的路由说明手册 route parameter docs,实际上可以通过约束和正则表达式实现很多不同的解决方案。

英文作者Chris Sevilleja  原文链接 http://scotch.io/bar-talk/understanding-laravel-route-parameters

译者:柳华芳 译文链接 https://it.liuhuafang.com/code/3398

柳华芳
柳华芳

奔向光明之地

文章: 1201
订阅评论
提醒
guest

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

0 评论
内联反馈
查看所有评论
0
希望看到您的想法,请您发表评论x