Home > PHP Framework > Laravel > body text

Let's talk about how to use resource routing in laravel

PHPz
Release: 2023-04-14 17:37:08
Original
1555 people have browsed it

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');
Copy after login

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'
]]);
Copy after login

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

  1. 自定义路由方法

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

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

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

  1. 自定义资源参数

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

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

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

四、Laravel资源路由实战

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

Route::resource('notes', 'NoteController');
Copy after login

接下来,我们创建一个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');
    }
}
Copy after login

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

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

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

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

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <h1>New Note:</h1>
                <hr>
                <form method="post" action="/notes">
                    {{csrf_field()}}
                    <div class="form-group">
                        <label for="title">Title</label>
                        <input type="text" class="form-control" name="title" id="title" placeholder="Enter the title">
                    </div>
                    <div class="form-group">
                        <label for="content">Content</label>
                        <textarea class="form-control" name="content" id="content" placeholder="Enter the content"></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>
@endsection
Copy after login
  1. resources/views/notes/show.blade.php:
@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <h1>Note Detail:</h1>
                <hr>
                <h2>Title:</h2>
                <p>{{$note->title}}</p>
                <h2>Content:</h2>
                <p>{{$note->content}}</p>
                <a href="/notes/{{$note->id}}/edit" class="btn btn-primary">Edit</a>
                <form method="post" action="/notes/{{$note->id}}" style="display: inline-block;">
                    {{csrf_field()}}
                    {{method_field('DELETE')}}
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
@endsection
Copy after login
  1. resources/views/notes/edit.blade.php:
@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <h1>Edit Note:</h1>
                <hr>
                <form method="post" action="/notes/{{$note->id}}">
                    {{csrf_field()}}
                    {{method_field('PUT')}}
                    <div class="form-group">
                        <label for="title">Title</label>
                        <input type="text" class="form-control" name="title" id="title" value="{{$note->title}}">
                    </div>
                    <div class="form-group">
                        <label for="content">Content</label>
                        <textarea class="form-control" name="content" id="content">{{$note->content}}</textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">Update</button>
                </form>
            </div>
        </div>
    </div>
@endsection
Copy after login

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

最后,我们运行服务器并访问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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!