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 Primary Function: Backend DevelopmentLaravel's Primary Function: Backend DevelopmentApr 15, 2025 am 12:14 AM

Laravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.

Laravel's Backend Capabilities: Databases, Logic, and MoreLaravel's Backend Capabilities: Databases, Logic, and MoreApr 14, 2025 am 12:04 AM

Laravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.

Laravel's Versatility: From Simple Sites to Complex SystemsLaravel's Versatility: From Simple Sites to Complex SystemsApr 13, 2025 am 12:13 AM

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

Laravel (PHP) vs. Python: Development Environments and EcosystemsLaravel (PHP) vs. Python: Development Environments and EcosystemsApr 12, 2025 am 12:10 AM

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

Laravel and the Backend: Powering Web Application LogicLaravel and the Backend: Powering Web Application LogicApr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Why is Laravel so popular?Why is Laravel so popular?Apr 02, 2025 pm 02:16 PM

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Which is better, Django or Laravel?Which is better, Django or Laravel?Mar 28, 2025 am 10:41 AM

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

Which is better PHP or Laravel?Which is better PHP or Laravel?Mar 27, 2025 pm 05:31 PM

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development 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