laravel 路由_简单的Laravel路由

庄宇
2023-12-01

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 page

    404页
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') }} 。 但是,这不适用于首页或关于页面,因为我们没有为其命名。

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 posts
    Route::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 posts
        if ($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 page
    Route::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 page
    Route::get('login', function()
    {
        // show the login page (app/views/login.blade.php)
        return View::make('login');
    });

    // process the login
    Route::post('login', function()
    {
        // validate
        // process login
        // if successful, redirect
        return 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 form
        Route::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 message
            Session::flash('message', 'Successfully created post!');

            // redirect
            return 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 error
        return 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 posts
    Route::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 posts
        if ($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 form
        Route::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 message
            Session::flash('message', 'Successfully created post!');

            // redirect
            return Redirect::to('admin/posts/create');
        });
    });

    // ===============================================
    // 404 ===========================================
    // ===============================================

    App::missing(function($exception)
    {

        // shows an error page (app/views/error.blade.php)
        // returns a page not found error
        return 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 路由

 类似资料: