Table of Contents
Write a New Article
Home Backend Development PHP Tutorial Laravel 5框架学习之表单_PHP

Laravel 5框架学习之表单_PHP

May 30, 2016 am 08:47 AM

首先让我们修改路由,能够增加一个文章的发布。

代码如下:


Route::get('articles/create', 'ArticlesController@create');

然后修改控制器

代码如下:


    public function create() {
        return view('articles.create');
    }

我们返回一个视图,新建这个视图。我们当然可以直接使用HTML建立表单,但我们有功能更好的办法。我们使用一个开源库,Jeffrey Way 开发的illuminate\html。安装依赖库:

代码如下:


composer require illuminate/html

laravel的库需要注册到laravel中才能使用。在 config/app.php 中,我们可以看到 laravel 提供的 provider 字段,这里描述了laravel的库功能。在Laravel Framewirk Service Providers... 最后添加我们新增的 HtmlProvider

代码如下:


'Illuminate\Html\HtmlServiceProvider',

我们不希望使用 Illuminate\Html\FromFacade 这么长的名字来引入,我们需要简短的名字。在当前的 app.php 中找到 aliases 段,在最后添加别名。

代码如下:


'Form'      => 'Illuminate\Html\FormFacade',
'Html'      => 'Illuminate\Html\HtmlFacade',

OK,现在我们来创建视图,views/articles/create.blade.php

@extends('layout')

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

  <hr/>

  {{--使用我们添加的 illuminate\html 开源库--}}
  {!! Form::open() !!}

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

@stop
Copy after login

访问 /articles/create 看到了错误,Why? 让我们测试一下,到底是哪里出了问题。在控制器中做出下面的修改:

  public function show($id) {
    dd('show');
    
    $article = Article::findOrFail($id);

    return view('articles.show', compact('article'));
  }
Copy after login


没错,你没看错,就是在 show 方法中添加 dd() 方法,这个方法简单的输出一个信息然后死掉。我们再来访问 /articles/create ,你看到了什么,你看到输出了 show 。

为什么我们访问 create 结果路由给了我们 show ? 我们来查看一下路由,到底发生了什么。

代码如下:


Route::get('articles', 'ArticlesController@index');
Route::get('articles/{id}', 'ArticlesController@show');
Route::get('articles/create', 'ArticlesController@create');

上面是我们的路由,注意到 articles/{id} 意味着这是一个通配符,所有在 articles/ 后面的东西都会匹配,你知道了么?我们的 /articles/create 也被他匹配了。OMG!

解决方案就是调整顺序:

代码如下:


Route::get('articles', 'ArticlesController@index');
Route::get('articles/create', 'ArticlesController@create');
Route::get('articles/{id}', 'ArticlesController@show');

也就是从特殊到普通,以后的路由设置中要时刻注意这个问题。现在我们在访问 articles/create 一切OK了。

在浏览器中查看一下源代码,你会发现不仅生成了 method 和 action 同时生成了一个隐藏的 _token 字段作为服务器对窗体的验证,避免黑客的伪造攻击。

让我们修改我们的视图,添加字段:

@extends('layout')

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

  <hr/>

  {{--使用我们添加的 illuminate\html 开源库--}}
  {!! Form::open() !!}
    <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::submit('Add Article', ['class' => 'btn btn-primary form-control']) !!}
    </div>

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

@stop
Copy after login


当表单提交的时候,实际上是使用 post 方法提交到 articles/create 上的,但根据RESTful的习惯,我们希望能够 post 到 /articles 上,我们来修改视图的表单方法,设定提交的路径。

代码如下:


{!! Form::open(['url' => 'articles']) !!}

然后我们在路由中处理表单提交事件。

代码如下:


Route::post('/articles', 'ArticlesController@store');

我们来处理控制器

//注意:将下面的 use 语句删除,我们使用 facade 接口中的 Request
//use App\Http\Requests\Request;

//引入下面的命名空间中的 Request
use Illuminate\Support\Facades\Request;

  public function store() {
    //使用 Illuminate\Html\Request 来返回全部的表单输入字段
    $input = Request::all();

    //我们直接返回$input,来看一下
    return $input;
  }

Copy after login

我们可以直接看到输入表单的json结果。如果只需要 title 字段的值,则可以使用 Request::get('titel') 。

如何添加到数据库中呢?借助模型,我们可以直接采用下面的方法,

Article::create($input);
Copy after login

就这么简单,就是这么任性

如果没有忘记 Mass Assignment,在我们的模型中我们定义了 $fillable 数组,来定义那些字段可以直接在 create 的时候直接填充。

修改控制器,添加到模型中,并存储到数据库。

  public function store() {
    $input = Request::all();
    Article::create($input);

    return redirect('articles');
  }

Copy after login

添加一条记录试试,非常棒。但别忘了。我们还有一个字段叫做 published_at ,让我们来处理它。

  public function store() {
    $input = Request::all();
    $input['published_at'] = Carbon::now();

    Article::create($input);
    
    return redirect('articles');
  }

Copy after login

添加新纪录在测试一下。

还有一个问题,新添加的应该显示在最前面,我们来修改以下控制器。

 public function index() {
    //倒序获取文章
    //可以这样
    //$articles = Article::orderBy('published_at', 'desc')->get();
    //简单方式,当然还有 oldest()
    $articles = Article::latest('published_at')->get();

    return view('articles.index', compact('articles'));
  }
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 Article

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

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)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

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

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

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.

See all articles