search
HomePHP FrameworkLaravelLet's talk about how to use resource routing in laravel

As a mainstream web application development framework, Laravel can help developers create web applications quickly and efficiently. Among them, Resource Routes is a very useful feature in the Laravel framework. It can help developers easily define the URL routes required in the project, reduce development difficulty, and simplify code implementation. In this article, we will look at using Laravel resource routing to help developers understand how it works and how to use it in their projects.

1. What are Laravel resource routes (Resource Routes)?

In the Laravel framework, resource routes (Resource Routes) are a special routing type that allow developers to bind URL routes and controller methods together, so that developers can easily create CRUD (Create, Read, Update, Delete) operation.

When using resource routing, developers only need to define a route in the routes/web.php file, and Laravel will automatically generate 7 basic CRUD operation methods for the route, as well as the appropriate route name. This greatly simplifies code implementation and reduces development difficulty. In short, using Laravel resource routing can greatly improve development efficiency.

2. Basic syntax of resource routing

The basic syntax of Laravel resource routing is as follows:

Route::resource('resource_name', 'ResourceController');

Among them, 'resource_name' represents the resource name and 'ResourceController' represents the control device name.

Laravel will automatically generate 7 RESTful routes based on this resource name, which correspond to the 7 basic CRUD operations, as shown below:

##GET/resource_name/createcreateresource_name.createPOST/resource_namestoreresource_name.storeGET/resource_name/{resource_name}showresource_name.show##GET##PUT/PATCH/resource_name/{resource_name}updateresource_name.updateDELETE/resource_name/{resource_name}destroyresource_name .destroy

至此,我们了解了Laravel资源路由的基本语法和7个基本的RESTful路由。但是,有时候在项目中,我们需要自定义路由名称,或者修改路由方法。下面,我们将详细讲解如何自定义Laravel资源路由。

三、自定义Laravel资源路由

在Laravel中,我们可以通过修改资源参数来自定义资源路由。下面,我们以'articles'为例,介绍自定义Laravel资源路由的三种方法。

  1. 自定义路由名称

如果我们不想使用Laravel默认的路由名称,可以使用'as'命令来自定义路由名称。如下所示:

Route::resource('articles', 'ArticleController', ['names' => [
    'create' => 'articles.build',
    'edit' => 'articles.modify'
]]);

这里,我们定义了自定义路由名称'articles.build'和'articles.modify',它们分别对应于"articles/create"和"articles/{id}/edit"这两条路由。

  1. 自定义路由方法

除了自定义路由名称外,我们还可以通过修改资源参数来自定义路由方法。如下所示:

Route::resource('articles', 'ArticleController', ['only' => [
    'index', 'show'
]]);

这里,我们只定义了'index'和'show'这两个路由方法,因此'Laravel'会生成对应的'GET /articles'和'GET articles/{id}'两个路由,并且隐藏默认的路由名称。

  1. 自定义资源参数

如果我们不想使用'Laravel'默认的资源参数'id',可以使用'parameters'命令来自定义资源参数。如下所示:

Route::resource('articles', 'ArticleController', ['parameters' => [
    'articles' => 'post'
]]);

这里,我们将资源名称'articles'修改为'post',这样'Laravel'会接收到类似于'POST /post'这种请求,并将'id'参数绑定到控制器方法中。

四、Laravel资源路由实战

在本节中,我们将使用Laravel资源路由来创建一个简单的在线笔记应用程序。首先,在routes/web.php文件中定义资源路由,如下所示:

Route::resource('notes', 'NoteController');

接下来,我们创建一个NoteController,定义资源路由中7个基本的RESTful路由的实现方法。如下所示:

class NoteController extends Controller
{
    // 获取笔记列表
    public function index()
    {
        // 获取所有笔记记录
        $notes = Note::all();

        // 返回笔记记录列表视图
        return view('notes.index', compact('notes'));
    }

    // 显示笔记创建视图
    public function create()
    {
        // 返回笔记创建视图
        return view('notes.create');
    }

    // 创建新笔记
    public function store(Request $request)
    {
        // 数据验证
        $request->validate([
            'title' => 'required|max:255',
            'content' => 'required',
        ]);

        // 创建新笔记并保存到数据库
        $note = new Note();
        $note->title = $request->input('title');
        $note->content = $request->input('content');
        $note->save();

        // 重定向到笔记列表页面
        return redirect('/notes');
    }

    // 获取指定笔记详情
    public function show(Note $note)
    {
        // 返回指定笔记记录视图
        return view('notes.show', compact('note'));
    }

    // 显示笔记编辑视图
    public function edit(Note $note)
    {
        // 返回笔记编辑视图
        return view('notes.edit', compact('note'));
    }

    // 更新指定笔记
    public function update(Request $request, Note $note)
    {
        // 数据验证
        $request->validate([
            'title' => 'required|max:255',
            'content' => 'required',
        ]);

        // 更新指定笔记并保存到数据库
        $note->title = $request->input('title');
        $note->content = $request->input('content');
        $note->save();

        // 重定向到笔记列表页面
        return redirect('/notes');
    }

    // 删除指定笔记
    public function destroy(Note $note)
    {
        // 删除指定笔记记录
        $note->delete();

        // 重定向到笔记列表页面
        return redirect('/notes');
    }
}

在NoteController中,我们实现了7个基本的CRUD操作方法,分别对应于7个资源路由。其中,我们使用了Laravel自带的表单验证来验证用户输入的数据,以确保数据的准确性和完整性。

最后,在resources/views目录中创建7个视图文件,对应于7个基本的CRUD操作。如下所示:

  1. resources/views/notes/index.blade.php:
@extends('layouts.app')

@section('content')
    <div>
        <div>
            <div>
                <h1 id="Laravel-Resource-Route-Demo">Laravel Resource Route Demo</h1>
                <hr>
                <h2 id="Note-List">Note List:</h2>
                <ul>
                    @foreach($notes as $note)
                        <li><a>id}}">{{$note->title}}</a></li>
                    @endforeach
                </ul>
            </div>
        </div>
    </div>
@endsection
  1. resources/views/notes/create.blade.php:
@extends('layouts.app')

@section('content')
    <div>
        <div>
            <div>
                <h1 id="New-Note">New Note:</h1>
                <hr>
                <form>
                    {{csrf_field()}}
                    <div>
                        <label>Title</label>
                        <input>
                    </div>
                    <div>
                        <label>Content</label>
                        <textarea></textarea>
                    </div>
                    <button>Submit</button>
                </form>
            </div>
        </div>
    </div>
@endsection
  1. resources/views/notes/show.blade.php:
@extends('layouts.app')

@section('content')
    <div>
        <div>
            <div>
                <h1 id="Note-Detail">Note Detail:</h1>
                <hr>
                <h2 id="Title">Title:</h2>
                <p>{{$note->title}}</p>
                <h2 id="Content">Content:</h2>
                <p>{{$note->content}}</p>
                <a>id}}/edit" class="btn btn-primary">Edit</a>
                <form>id}}" style="display: inline-block;">
                    {{csrf_field()}}
                    {{method_field('DELETE')}}
                    <button>Delete</button>
                </form>
            </div>
        </div>
    </div>
@endsection
  1. resources/views/notes/edit.blade.php:
@extends('layouts.app')

@section('content')
    <div>
        <div>
            <div>
                <h1 id="Edit-Note">Edit Note:</h1>
                <hr>
                <form>id}}">
                    {{csrf_field()}}
                    {{method_field('PUT')}}
                    <div>
                        <label>Title</label>
                        <input>title}}">
                    </div>
                    <div>
                        <label>Content</label>
                        <textarea>{{$note->content}}</textarea>
                    </div>
                    <button>Update</button>
                </form>
            </div>
        </div>
    </div>
@endsection

上面这四个视图文件分别对应于显示笔记列表、显示创建笔记表单、显示笔记详细信息和编辑笔记功能。

最后,我们运行服务器并访问http://localhost:8000/notes即可看到演示效果。

总结

本文我们介绍了Laravel资源路由的基本用法和语法规则。我们从什么是Laravel资源路由开始,深入到如何使用Laravel资源路由创建CRUD工具,以及如何自定义Laravel资源路由。最后,通过笔记应用程序的演示,加深了对于Laravel资源路由的理解。现在,你掌握了使用Laravel资源路由构建高效Web应用程序的核心知识,可以应用到实际项目中了。

Method URI Action Name
GET /resource_name index resource_name.index
/resource_name/{resource_name} /edit edit resource_name.edit

The above is the detailed content of Let's talk about how to use resource routing in laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Laravel's Impact: Simplifying Web DevelopmentLaravel's Impact: Simplifying Web DevelopmentApr 21, 2025 am 12:18 AM

Laravel stands out by simplifying the web development process and delivering powerful features. Its advantages include: 1) concise syntax and powerful ORM system, 2) efficient routing and authentication system, 3) rich third-party library support, allowing developers to focus on writing elegant code and improve development efficiency.

Laravel: Frontend or Backend? Clarifying the Framework's RoleLaravel: Frontend or Backend? Clarifying the Framework's RoleApr 21, 2025 am 12:17 AM

Laravelispredominantlyabackendframework,designedforserver-sidelogic,databasemanagement,andAPIdevelopment,thoughitalsosupportsfrontenddevelopmentwithBladetemplates.

Laravel vs. Python: Exploring Performance and ScalabilityLaravel vs. Python: Exploring Performance and ScalabilityApr 21, 2025 am 12:16 AM

Laravel and Python have their own advantages and disadvantages in terms of performance and scalability. Laravel improves performance through asynchronous processing and queueing systems, but due to PHP limitations, there may be bottlenecks when high concurrency is present; Python performs well with the asynchronous framework and a powerful library ecosystem, but is affected by GIL in a multi-threaded environment.

Laravel vs. Python (with Frameworks): A Comparative AnalysisLaravel vs. Python (with Frameworks): A Comparative AnalysisApr 21, 2025 am 12:15 AM

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

Frontend with Laravel: Exploring the PossibilitiesFrontend with Laravel: Exploring the PossibilitiesApr 20, 2025 am 12:19 AM

Laravel can be used for front-end development. 1) Use the Blade template engine to generate HTML. 2) Integrate Vite to manage front-end resources. 3) Build SPA, PWA or static website. 4) Combine routing, middleware and EloquentORM to create a complete web application.

PHP and Laravel: Building Server-Side ApplicationsPHP and Laravel: Building Server-Side ApplicationsApr 20, 2025 am 12:17 AM

PHP and Laravel can be used to build efficient server-side applications. 1.PHP is an open source scripting language suitable for web development. 2.Laravel provides routing, controller, EloquentORM, Blade template engine and other functions to simplify development. 3. Improve application performance and security through caching, code optimization and security measures. 4. Test and deployment strategies to ensure stable operation of applications.

Laravel vs. Python: The Learning Curves and Ease of UseLaravel vs. Python: The Learning Curves and Ease of UseApr 20, 2025 am 12:17 AM

Laravel and Python have their own advantages and disadvantages in terms of learning curve and ease of use. Laravel is suitable for rapid development of web applications. The learning curve is relatively flat, but it takes time to master advanced functions. Python's grammar is concise and the learning curve is flat, but dynamic type systems need to be cautious.

Laravel's Strengths: Backend DevelopmentLaravel's Strengths: Backend DevelopmentApr 20, 2025 am 12:16 AM

Laravel's advantages in back-end development include: 1) elegant syntax and EloquentORM simplify the development process; 2) rich ecosystem and active community support; 3) improved development efficiency and code quality. Laravel's design allows developers to develop more efficiently and improve code quality through its powerful features and tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function