laravel 路由

One of the coolest (arguably the coolest) features of Laravel is its amazing routing features. Coming from Codeigniter where all routing is done by controller and method names, this was a breath of fresh air. I like seeing a top down view of my application and where all the pages are, and the routes file is like staring down at a roadmap from the clouds.

Laravel最酷(也许最酷)的功能之一就是其惊人的路由功能。 来自Codeigniter,其中所有路由均由控制器和方法名称完成,这真是新鲜空气。 我喜欢看到我的应用程序以及所有页面的位置的俯视图,而routes文件就像从云中凝视着一个路线图。

Today, we will not only explore the types of routes and features like filters, we will look more closely at applying them to real world scenarios. These scenarios include:

今天,我们不仅将探索路由和过滤器等功能的类型,还将更加仔细地将其应用于现实世界中。 这些方案包括:

  • Routing for basic static pages基本静态页面的路由
  • Passing parameters to functions将参数传递给函数
  • Using named routes to make URLs easier to use使用命名路由使URL易于使用
  • Group routing组路由
  • Filtering routes for Auth or anything else过滤Auth或其他路由
  • Handling 404 Errors处理404错误
Routing to Controllers and Controllers will be handled more in depth in a totally separate article. So much info there that it deserves its own party. 到控制器和控制器的路由将在单独的文章中更深入地处理。 那里的信息太多,值得它自己来参加。

我们的应用 ( Our Application )

Let's create an imaginary application to test all of our routing. We'll make an online portfolio site with a blog and a backend admin section to add posts. Here are the guidelines for our little application.

让我们创建一个虚构的应用程序来测试所有路由。 我们将创建一个带有博客和后端管理部分的在线投资组合网站,以添加帖子。 这是我们的小应用程序的准则。

要求: (Requirements:)

  • Super cool name超级酷的名字
  • Basic pages (Home, About, Work)基本页面(主页,关于,工作)
  • Blog pages (main page and category page)博客页面(主页和类别页面)
  • Admin section (Authentication required)管理员部分(需要身份验证)
  • Login page for the admin section管理员部分的登录页面
  • 404 page404页
Routing Only This tutorial will only deal with the code associated with routing. More tutorials will follow to explain how to fully build a web application with all the glorious parts of Laravel. 仅路由本教程将仅处理与路由关联的代码。 接下来的更多教程将解释如何使用Laravel的所有出色部分完全构建Web应用程序。

Let's get started!

让我们开始吧!

超级酷的名字 ( Super Cool Name )

Naming your application is half the battle. Maybe not half, but it sure feels like it. Let's call this project Lagavulin.

命名应用程序是成功的一半。 也许不是一半,但肯定会喜欢。 我们将此项目Lagavulin

基本页面基本路由 ( Basic Pages Basic Routing )

Let's open up our app/routes.php file and get our static pages (Home, About, and Work) routed to. These will be the easiest since they don't really require anything other than their view. No login, no parameters, just good ol' displaying a page.

让我们打开app/routes.php文件,并将静态页面(“主页”,“关于”和“工作”)路由到。 这些将是最简单的,因为除了视图之外,它们实际上不需要任何其他内容。 没有登录,没有参数,只是显示页面好。

Delete everything out of your routes.php and we will start fresh.

从您的routes.php中删除所有内容,我们将重新开始。

// app/routes.php
<?php// ===============================================// STATIC PAGES ==================================// ===============================================// show a static view for the home page (app/views/home.blade.php)Route::get('/', function(){return View::make('home');});// about page (app/views/about.blade.php)Route::get('about', function(){return View::make('about');});// work page (app/views/work.blade.php)Route::get('work', array('as' => 'work', function(){return View::make('work');}));

Now you can visit yoursite.com, yoursite.com/about, or yoursite.com/work.

现在,您可以访问yoursite.comyoursite.com/aboutyoursite.com/work

命名路由 (Named Routing)

You'll notice on the work route, we've added an array as. This creates a named route. With a named route, you can link to it in your application views using {{ URL::route('work') }}. This will not work for the home or about page, however, since we did not name them.

你会发现工作路线上,我们增加了一个数组as 。 这将创建一个命名路线 。 使用命名的路由,您可以使用{{ URL::route('work') }}在应用程序视图中链接到该{{ URL::route('work') }} 。 但是,这不适用于首页或关于页面,因为我们没有为其命名。

@media (max-width: 1280px) { .go-go-gadget-react img:first-child { display: none; } }@media (max-width: 780px) {.go-go-gadget-react { flex-direction: column; }.go-go-gadget-react img { margin-left: 0 !important; margin-bottom: 12px !important; }.header-thingy { margin-top: 20px; }.button-thingy { margin-left: 0 !important; margin-top: 12px !important; }} @media (max-width: 1280px) { .go-go-gadget-react img:first-child { display: none; } }@media (max-width: 780px) {.go-go-gadget-react { flex-direction: column; }.go-go-gadget-react img { margin-left: 0 !important; margin-bottom: 12px !important; }.header-thingy { margin-top: 20px; }.button-thingy { margin-left: 0 !important; margin-top: 12px !important; }}

The home and about pages will need to be linked to using {{ URL::to('/') }} and {{ URL::to('about') }}. The benefit of a named route is that even if you change the location of the route, as long as the name stays the same, the link will still work.

家庭有关的网页将需要连接到使用{{ URL::to('/') }}{{ URL::to('about') }} 命名路由的好处在于,即使您更改了路由的位置,只要名称保持不变,链接仍然可以使用。

Here's a little table to shows why named routes are great. Hint: You don't have to go through your entire application spend time changing links.

这是一张小表,显示为什么命名路由很棒。 提示:您不必遍历整个应用程序而花费时间更改链接。

<td>Changed To</td><td>Works?</td>
</tr>
<td>Route::get('about-us')...</td><td class="danger">{{ URL::to('about') }}</td>
</tr><tr><td>Route::get('work', array('as' => 'work'...</td><td>Route::get('our-work', array('as' => 'work'...</td><td class="success">{{ URL::route('work') }}</td>
</tr>
Original
Route::get('about')...
原版的
路线:: get('about')...

That's it for static pages. Laravel uses closures to handle routes. You can return anything you want here. In our case, we wanted to return a view file since these are just boring static pages.

静态页面就是这样。 Laravel使用闭包来处理路由。 您可以在这里退还任何物品。 在我们的例子中,我们想返回一个视图文件,因为这些只是无聊的静态页面。

具有类别路由参数的博客页面 ( Blog Pages with Categories Route Parameters )

Now we're past the easy peazy static page routing. Our blog pages will need more than just static pages. They will need information from the database like our posts which include pictures, content, title, author, date, etc...

现在,我们已经完成了简单的静态静态页面路由。 我们的博客页面将不仅需要静态页面。 他们将需要数据库中的信息,例如我们的帖子,其中包括图片,内容,标题,作者,日期等。

We will create one route to handle all our blog stuff. This route uses optional route parameters to check if there are categories present. If there is a category, it will pull those blog posts. If not, it will show all posts.

我们将创建一条处理所有博客内容的途径。 该路由使用可选的路由参数来检查是否存在类别。 如果有一个类别,它将拉那些博客文章。 如果没有,它将显示所有帖子。

To make the category required, just take out the ? and = null.

要使类别成为必需,只需删除?= null

// app/routes.php
<?php...// ===============================================// BLOG PAGES ====================================// ===============================================// blogroll to show all blog postsRoute::get('blog/{category?}', function($category = null){// get all the blog stuff from database// if a category was passed, use that// if no category, get all postsif ($category)$posts = Post::where('category', '=', $category);else$posts = Post::all();// show the view with blog posts (app/views/blog.blade.php)return View::make('blog')->with('posts', $posts);});

You can break this down into separate routes if you like. This can make things cleaner for you if you need to have different styled views based on category or any other special things.

您可以根据需要将其分解为单独的路线。 如果您需要基于类别或任何其他特殊内容的不同样式的视图,这可以使您的工作更干净。

We get all the blog posts using Eloquent ORM You have other options for accessing the database, but since we're just explaining routes, we'll keep it simple. We'll talk more on Eloquent and that database stuff later. That wraps it up for our blog pages.

我们使用Eloquent ORM获取所有博客文章。还有其他访问数据库的选项,但是由于我们只是在解释路线,因此我们将使其保持简单。 稍后,我们将详细介绍Eloquent和该数据库。 这样就构成了我们的博客页面。

管理部分组路由,路由前缀和身份验证过滤器 ( Admin Section Group Routing, Route Prefixing, and Auth Filters )

Our blog needs an admin section so we can add posts. It needs to be protected from the crazy people in the world so we'll add authentication requirements. We also want all our URLs to start with /admin.

我们的博客需要一个管理部分,因此我们可以添加帖子。 需要保护它免受世界上疯狂的人们的侵害,因此我们将添加身份验证要求。 我们还希望所有URL以/admin开头。

Route groups are a great way to apply the same prefixes, filters, or anything else to a group of routes. Read more about route groups.

路由组是将相同的前缀,过滤器或其他任何内容应用到一组路由的一种好方法。 阅读有关路线组的更多信息。

Route prefixing will allow us to add /admin to the beginning of all admin routes. This way, we won't have to do Route::get('admin/something')... every time. Read more about prefixing.

路由前缀将使我们能够将/admin添加到所有管理路由的开头。 这样,我们就不必每次都执行Route::get('admin/something')... 了解有关前缀的更多信息。

// app/routes.php
<?php...// ===============================================// ADMIN SECTION =================================// ===============================================Route::group(array('prefix' => 'admin'), function(){// main page for the admin section (app/views/admin/dashboard.blade.php)Route::get('/', function(){return View::make('admin.dashboard');});// subpage for the posts found at /admin/posts (app/views/admin/posts.blade.php)Route::get('posts', function(){return View::make('admin.posts');});// subpage to create a post found at /admin/posts/create (app/views/admin/posts-create.blade.php)Route::get('posts/create', function(){return View::make('admin.posts-create');});});

Auth filters will be applied to the entire group to protect the entire admin section. You can create your own filters and do anything you like to limit access to a route. For our purposes, we will use the before Read more about filters.

身份验证过滤器将应用于整个组,以保护整个管理员部分。 您可以创建自己的过滤器,并做任何想限制访问路由的操作。 出于我们的目的,我们将使用before有关滤镜的信息 。

We will add the auth filter, which is already defined in app/filters.php to our group. This will redirect a user to /login if they are not logged in. Let's add the auth filter to the group and add a route for the login page.

我们将把已经在app/filters.php定义的auth过滤器添加到我们的组中。 如果用户未登录,这会将用户重定向到/ login。让我们将auth过滤器添加到组中,并为登录页面添加路由。

// app/routes.php
<?php...// ===============================================// LOGIN SECTION =================================// ===============================================// show the login pageRoute::get('login', function(){// show the login page (app/views/login.blade.php)return View::make('login');});// ===============================================// ADMIN SECTION =================================// ===============================================Route::group(array('prefix' => 'admin', 'before' => 'auth'), function(){// main page for the admin section (app/views/admin/dashboard.blade.php)Route::get('/', function(){return View::make('admin.dashboard');});...});

Now if somebody tries to access lagavulin.com/admin or lagavulin.com/admin/posts, they will be redirected to the login page.

现在,如果有人尝试访问lagavulin.com/adminlagavulin.com/admin/posts ,他们将被重定向到登录页面。

登录表单POST路由 ( Login Form POST Routing )

We will need to validate and process the login form. Let's make a quick route to do that and use Redirect::intended() to redirect them back to their intended destination before our filter so kindly kicked them to the login page.

我们将需要验证和处理登录表单。 让我们做一个快速的方法来做到这一点,并使用Redirect::intended()将它们重定向回其预期的目的地,然后再过滤器将它们踢到登录页面。

// app/routes.php
<?php...// ===============================================// LOGIN SECTION =================================// ===============================================// show the login pageRoute::get('login', function(){// show the login page (app/views/login.blade.php)return View::make('login');});// process the loginRoute::post('login', function(){// validate// process login// if successful, redirectreturn Redirect::intended();});// ===============================================// ADMIN SECTION =================================// ===============================================...}));

For more information on processing the login, check out our Laravel Login Tutorial.

有关处理登录的更多信息,请查看我们的Laravel登录教程 。

创建博客文章 (Creating Blog Posts)

Now that we've seen how POST routing works, let's handle creating the new blog post form. The Route::get('posts/create')... will show the form. In our form action, we can set it to <form action="/admin/posts/create">. Let's add a route to process the form, and show a message that the post was saved.

现在我们已经了解了POST路由的工作原理,让我们来处理创建新的博客文章表单。 Route::get('posts/create')...将显示表单。 在我们的表单操作中,我们可以将其设置为<form action="/admin/posts/create"> 。 让我们添加一条处理表单的路线,并显示一条消息,指出帖子已保存。

// app/routes.php
<?php...// ===============================================// ADMIN SECTION =================================// ===============================================Route::group(array('prefix' => 'admin', 'before' => 'auth'), function(){...// subpage to create a post found at /admin/posts/create (app/views/admin/posts-create.blade.php)Route::get('posts/create', function(){return View::make('admin.posts-create');});// process the create blog post formRoute::post('posts/create', function(){// add the post to the database// $post = new Post;// $post->title = Input::get('title');// more stuff here// $post->save();// create a success messageSession::flash('message', 'Successfully created post!');// redirectreturn Redirect::to('admin/posts/create');});});

Processing forms and saving to the database is easy and fun. We'll get to it in the next few Laravel posts. Now that we have static pages, blog pages, admin section and blog post creation, let's handle 404 errors.

处理表格并将其保存到数据库既简单又有趣。 我们将在接下来的Laravel文章中介绍它。 现在我们有了静态页面,博客页面,管理部分和博客文章创建,现在让我们处理404错误。

404错误 ( 404 Errors )

404 Errors are very easy to handle. We'll add a simple route to the end of our routes.php file and call it a day. To read up more on handling all sorts of errors, read the error docs.

404错误非常容易处理。 我们将在路由文件的末尾添加一条简单的路由,并将其命名为“ day”。 要阅读有关处理各种错误的更多信息,请阅读错误文档。

// app/routes.php
<?php...// ===============================================// 404 ===========================================// ===============================================App::missing(function($exception){// shows an error page (app/views/error.blade.php)// returns a page not found errorreturn Response::view('error', array(), 404);});

结论 ( Conclusion )

As you can see, Laravel makes it very easy to lay the foundation of your entire site in the routes.php file. You can see every page, section, authorization requirements, and handle RESTful routes. This helps us to maintain our application from this file and really get a vision of how everything works together.

如您所见,Laravel使您可以轻松地在routes.php文件中奠定整个站点的基础。 您可以查看每个页面,每个部分,授权要求,以及处理RESTful路由。 这有助于我们从该文件维护我们的应用程序,并真正了解一切如何协同工作。

Here is the full code for our routes.php file now. We were able to set the foundation for a blog and portfolio site with an authenticated admin section!

现在是我们的routes.php文件的完整代码。 我们能够通过经过身份验证的管理部分为博客和投资组合网站奠定基础!

// app/routes.php
<?php// ===============================================// STATIC PAGES ==================================// ===============================================// show a static view for the home page (app/views/home.blade.php)Route::get('/', function(){return View::make('home');});// about page (app/views/about.blade.php)Route::get('about', function(){return View::make('about');});// work page (app/views/work.blade.php)Route::get('work', array('as' => 'work', function(){return View::make('work');}));// ===============================================// BLOG PAGES ====================================// ===============================================// blogroll to show all blog postsRoute::get('blog/{category?}', function($category = null){// get all the blog stuff from database// if a category was passed, use that// if no category, get all postsif ($category)$posts = Post::where('category', '=', $category);else$posts = Post::all();// show the view with blog posts (app/views/blog.blade.php)return View::make('blog')->with('posts', $posts);});// ===============================================// ADMIN SECTION =================================// ===============================================Route::group(array('prefix' => 'admin'), function(){// main page for the admin section (app/views/admin/dashboard.blade.php)Route::get('/', function(){return View::make('admin.dashboard');});// subpage for the posts found at /admin/posts (app/views/admin/posts.blade.php)Route::get('posts', function(){return View::make('admin.posts');});// subpage to create a post found at /admin/posts/create (app/views/admin/posts-create.blade.php)Route::get('posts/create', function(){return View::make('admin.posts-create');});// process the create blog post formRoute::post('posts/create', function(){// add the post to the database// $post = new Post;// $post->title = Input::get('title');// more stuff here// $post->save();// create a success messageSession::flash('message', 'Successfully created post!');// redirectreturn Redirect::to('admin/posts/create');});});// ===============================================// 404 ===========================================// ===============================================App::missing(function($exception){// shows an error page (app/views/error.blade.php)// returns a page not found errorreturn Response::view('error', array(), 404);});

下一步是什么? ( What's Next? )

There are many things we can do to improve upon this. Since we only dealt with routing, we didn't get to dive in depth or leverage other great features like:

我们可以做很多事情来改善这一点。 因为我们只处理路由,所以我们没有深入研究或利用其他出色的功能,例如:

  • Controllers (Resource and RESTful)控制器(资源和RESTful)
  • Eloquent雄辩
  • Authentication认证方式

We will be working on a whole Laravel series of articles. Let us know in the comments what you would like to see, or if you have any questions.

我们将撰写整个Laravel系列文章。 在评论中让我们知道您想看到的内容,或有任何疑问。

翻译自: https://scotch.io/tutorials/simple-and-easy-laravel-routing

laravel 路由

laravel 路由_简单的Laravel路由相关推荐

  1. laravel 模型里自定义属性_关于Laravel 7 的简单隐式路由模型绑定

    Laravel 的下一个主要发行版本 ,你可以直接在路由定义中自定义隐式路由模型绑定: Route::get('/posts/{post:slug}', function (Post $post) { ...

  2. php 隐式路由,关于Laravel 7 的简单隐式路由模型绑定

    搜索热词 Laravel 的下一个主要发行版本 ,你可以直接在路由定义中自定义隐式路由模型绑定: Route::get('/posts/{post:slug}',function (Post $pos ...

  3. laravel身份证验证_简单的Laravel登录身份验证

    laravel身份证验证 This article has been upgraded to work with Laravel 4.1.26 本文已升级为可与Laravel 4.1.26一起使用 T ...

  4. flask框架视图和路由_角度视图,路由和NgModule的解释

    flask框架视图和路由 Angular vs AngularJS (Angular vs AngularJS) AngularJS (versions 1.x) is a JavaScript-ba ...

  5. 华为防火墙做单臂路由_华为-VLAN间路由:VLANIF+单臂路由(子接口)-释然

    华为-VLAN间路由:VLANIF+单臂路由(子接口) 前言 之前已经讲解过了思科交换机的VLAN间路由以及路由器与二层交换机组网的单播路由形式[子接口],这次主要讲解华为上面的VLAN间路由的配置, ...

  6. 华为防火墙做单臂路由_华为单臂路由配置实例

    华为单臂路由实验配置(共8篇)华为 AR2200路由器单臂路由配置实例华为 AR2200路由器单臂路由配置实例作者:救世主220实验日期:2015 6 29实验拓扑如下:AR5配置:[AR5]dis ...

  7. 静态路由_配置IPv4静态路由

    组网需求 如图1所示,属于不同网段的主机通过几台Switch相连,要求不配置动态路由协议,使不同网段的任意两台主机之间能够互通. 图1 配置IP静态路由组网图 配置思路 采用如下的思路配置IPv4静态 ...

  8. 华为多臂路由_[分享]华为 AR路由 策略路由 多WAN环境下指定出口 | 霸王硬上弓's Blog...

    需要符合如下要求: 1.不同IP段走不同接口,指定IP的流量可以通过指定WAN,或者多WAN下自动选路/负载均衡(自动选路/负载均衡已配置好,略). 2.指定接口后实现内网的隔离/互联互通 操作环境: ...

  9. win10 软路由_超小软路由Nanopi R2S折腾记

    全世界只有不到0.00~1 % 的人关注了我们 得到你的关注是小帮的幸运 垂涎软路由已久,这次终于对它下手 因为是初次体验软路由,为了控制成本,本次选择了Nanopi r2s作为折腾对象,小巧精致的外 ...

  10. asuswrt 单臂路由_我的软路由折腾-斐讯N1单臂路由设置

    我的软路由折腾-斐讯N1单臂路由设置 2020-07-26 23:11:52 58点赞 738收藏 86评论 小编注:此篇文章来自即可瓜分10万金币,周边好礼达标就有,邀新任务奖励无上限,点击查看活动 ...

最新文章

  1. 英语语法总结--连词
  2. linux存储--inode详解(五)
  3. VMprotect静态跟踪 字节码反编译
  4. ITK:创建一个图像区域
  5. 如何编译Linux kernel
  6. BZOJ 2527 Meteors | 整体二分
  7. 什么是pytorch(3神经网络)(翻译)
  8. Android编译tcpdump,android 5.0以上使用tcpdump
  9. Android Lolipop 屏蔽隐式Intent检查引发的错误
  10. 为 Electron / Atom Shell 设置应用icon(应用图标)
  11. OpenCV官方教程节选
  12. 传智播客python高级-2018年传智播客黑马python15期
  13. 基因组测序 转录组测序
  14. PowerDNS Authoritative Server 3.2 RC3 发布
  15. 移动端适配方案(rem+flex)
  16. Latex大括号及多行公式
  17. 4.树和二叉树——数据结构 (严蔚敏C语言版)
  18. 机器人(自动化)课程的持续学习-2022-
  19. 架构集一---语音连麦聊天室实现方案分析
  20. jquery学习笔记及常用函数封装

热门文章

  1. Android Studio模拟器如何运行apk文件
  2. Pandas缺失值inf与nan处理实践
  3. Mac查看本地ip地址
  4. url“forum.php,如何让discuz论坛首页打开不显示forum.php的方法分享
  5. 在纯Win10环境下部署DzzOffice+OnlyOffice协同办公系统
  6. [转]PHP FFI详解 - 一种全新的PHP扩展方式
  7. 微信隐藏功能系列:微信状态里如何加音乐?有2个小技巧
  8. 随心所遇,随遇而安。
  9. PHP编程学习之路 2
  10. modbusx协议讲解