Table of Contents
Edit: {!! $article->title !!}
Write a New Article
Home Backend Development PHP Tutorial Laravel 5框架学习之子视图和表单复用_PHP

Laravel 5框架学习之子视图和表单复用_PHP

May 30, 2016 am 08:48 AM
php framework laravel

我们需要处理编辑文章的问题。当然我们可以手工添加新的路由,就像这样:

代码如下:


Route::get('/articles/{id}/edit', 'ArticleController@edit');

让我们在命令行下使用 artisan 的 route:list 来查看我们当前的路由:

代码如下:


php artisan route:list

在符合 RESTful 的情况下,可能直接使用 laravel 的 resource 路由是一种好的选择,然我们将所有的路由都去掉,只添加唯一的一个:

代码如下:


Route::resource('articles', 'ArticlesController');

再次使用 php artisan route:list 查看路由,哇,一堆的符合我们期望的路由产生了。每一项都仔细查看一下。

现在在控制器中添加方法:

  public function edit($id) {
    $article = Article::findOrFail($id);

    return view('articles.edit', compact('article'));
  }

Copy after login

现在创建视图

@extends('layout')

@section('content')
  <h1 id="Edit-article-title">Edit: {!! $article->title !!} </h1>

  <hr/>

  ...

Copy after login

好吧,我承认这些代码都是从 create.blade.php 中拷贝出来的,修改了一下,问题是我们需要重复吗?后面我们会处理这个问题,现在来看一下表单的提交问题。在路由中 php artisan route:list ,再看一遍,修改使用了 PATCH 方法,我们来修改视图:

代码如下:


{!! Form::open(['method' => 'PATCH', 'url' => 'articles/' . $article->id]) !!}

在浏览器中访问 /articles/1/edit ,查看一下源代码,发现laravel自动生成了 _method=PATCH 的隐藏字段。

一问题是,我们编辑文章,但是文章的信息并没有显示出来,我们修改一下视图:

代码如下:


{!! Form::model($article, ['method' => 'PATCH', 'url' => 'articles/' . $article->id]) !!}

OK,everything's ok,除了 published_on 字段仍然设置为当前日期,后面我们来处理。

现在在控制器中添加方法:

  public function update($id, \Illuminate\Http\Request $request) {
    $article = Article::findOrFail($id);
    $article->update($request->all());

    return redirect('articles');
  }

Copy after login

我们在修改的过程中也需要验证,让我们复用我们的 Request 类,将 CreateArticleRequest 更名为更通用的 ArticleRequest,别忘了修改 store 方法中的参数。

  public function update($id, Requests\ArticleRequest $request) {
    $article = Article::findOrFail($id);
    $article->update($request->all());

    return redirect('articles');
  }

Copy after login

现在剩下的问题是我们的新建和编辑使用了大部分相同的代码,比如显示错误,但他们存在两份,我们来修改这个问题。

我们直接在 views/articles 下面新建文件 list.blade.php,并把错误处理代码从 create.blade.php 中拷贝出来:

@if ($errors->any())
  <ul class="alert alert-danger">
    @foreach($errors->all() as $error)
      <li>{{ $error }}</li>
    @endforeach
  </ul>
@endif
Copy after login

在 create.blade.php 只需用下面语句替换错误处理代码即可:

代码如下:


@include('articles.list')

让我们再来处理表单代码,表单代码中除了 form 不大一样和提交按钮有区别,其他都差不多。我们创建一个视图 articles/form_partial.blade.php,将代码拷贝出来

<div class="form-group">
  {!! Form::label('title', 'Title:') !!}
  {!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
  {!! Form::label('body', 'Body:') !!}
  {!! Form::textarea('body', null, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
  {!! Form::label('published_at', 'Publish On:') !!}
  {!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
</div>

<div class="form-group">
  {{--这里要设置变量,依据是编辑还是修改来改变,当然也可以不放置在partial中--}}
  {!! Form::submit($submitButtonText, ['class' => 'btn btn-primary form-control']) !!}
</div>

Copy after login

修改 create.blade.php

@extends('layout')

@section('content')
  <h1 id="Write-a-New-Article">Write a New Article</h1>

  <hr/>

  @include('articles.list')

  {{--使用我们添加的 illuminate\html 开源库--}}
  {!! Form::open(['url' => 'articles']) !!}
    @include('articles.form_partial', ['submitButtonText' => 'Add Article'])
  {!! Form::close() !!}

@stop

Copy after login

修改 edit.blade.php

@extends('layout')

@section('content')
  <h1 id="Edit-article-title">Edit: {!! $article->title !!} </h1>

  <hr/>

  @include('articles.list')
  {{--使用我们添加的 illuminate\html 开源库--}}
  {!! Form::model($article, ['method' => 'PATCH', 'url' => 'articles/' . $article->id]) !!}
  @include('articles.form_partial', ['submitButtonText' => 'Update Article'])

  {!! Form::close() !!}

@stop
Copy after login

以上就是本文给大家介绍的全部内容了,希望能够对大家熟练掌握Laravel5框架有所帮助。

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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

See all articles