Home Backend Development PHP Tutorial Laravel 5 Basics (9) - Form

Laravel 5 Basics (9) - Form

Aug 08, 2016 am 09:26 AM
create form

First, let us modify the routing to add an article to publish.

<code>Route::get('articles/create', 'ArticlesController@create');</code>
Copy after login

Then modify the controller

<code>    public function create() {
        return view('articles.create');
    }</code>
Copy after login

We return a view and create a new view. Of course we could create the form directly using HTML, but we have a more functional way. We use an open source library, illuminatehtml developed by Jeffrey Way. Install dependent libraries:

<code>composer require illuminate/html</code>
Copy after login

Laravel’s library needs to be registered in laravel before it can be used. In config/app.php, we can see the provider field provided by laravel, which describes the library functions of laravel. In Laravel Framewirk Service Providers... finally add our new HtmlProvider

<code>'Illuminate\Html\HtmlServiceProvider',</code>
Copy after login

We don’t want to use a long name like IlluminateHtmlFromFacade to import, we need a short name. Find the aliases section in the current app.php and add the alias at the end.

<code>'Form'      => 'Illuminate\Html\FormFacade',
'Html'      => 'Illuminate\Html\HtmlFacade',</code>
Copy after login

OK, now let’s create the view, views/articles/create.blade.php

<code>@extends('layout')

@section('content')
    <h1>Write a New Article</h1>

    <hr/>

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

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

@stop</code>
Copy after login

Visit /articles/create and see the error, Why? Let’s test it to see what went wrong. Make the following changes in the controller:

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

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

That’s right, you read that right, just add the dd() method to the show method. This method simply outputs a message and then dies. Let’s visit /articles/create again. What do you see? You see the output show.

Why did we access create and the resulting route gave us show? Let’s check the route and see what happened.

<code>Route::get('articles', 'ArticlesController@index');
Route::get('articles/{id}', 'ArticlesController@show');
Route::get('articles/create', 'ArticlesController@create');</code>
Copy after login

The above is our route, notice that articles/{id} means this is a wildcard, everything after articles/ will match, did you know? Our /articles/create was also matched by him. OMG!

The solution is to adjust the order:

<code>Route::get('articles', 'ArticlesController@index');
Route::get('articles/create', 'ArticlesController@create');
Route::get('articles/{id}', 'ArticlesController@show');</code>
Copy after login

That is, from special to ordinary, you should always pay attention to this issue in future routing settings. Now we are accessing articles/create and everything is OK.

Check the source code in the browser, you will find that not only method and action are generated, but also a hidden _token field is generated as the server verifies the form to avoid forgery attacks by hackers.

Let’s modify our view and add fields:

<code>@extends('layout')

@section('content')
    <h1>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</code>
Copy after login

When the form is submitted, it is actually submitted to articles/create using the post method, but according to RESTful habits, we hope to be able to post to /articles, let’s modify the form of the view Method to set the submission path.

<code>{!! Form::open(['url' => 'articles']) !!}</code>
Copy after login

Then we handle the form submission event in the route.

<code>Route::post('/articles', 'ArticlesController@store');</code>
Copy after login

Let’s deal with the controller

<code>
//注意:将下面的 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;
    }</code>
Copy after login

We can directly see the json result of the input form. If you only need the value of the title field, you can use Request::get('titel') .

How to add it to the database? With the help of the model, we can directly adopt the following method,

<code>Article::create($input);</code>
Copy after login

It’s that simple, it’s that willful

If we didn’t forget Mass Assignment, we defined the $fillable array in our model to define those fields that can be filled directly during create.

Modify the controller, add it to the model, and store it in the database.

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

        return redirect('articles');
    }</code>
Copy after login

Try adding a record, it’s great. But don't forget. We also have a field called published_at , let’s deal with that.

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

        Article::create($input);
        
        return redirect('articles');
    }</code>
Copy after login

Add a new record and test it.

There is another problem, the newly added one should be displayed at the front, let’s modify the following controller.

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

        return view('articles.index', compact('articles'));
    }</code>
Copy after login

The above introduces the basics of Laravel 5 (9) - Form, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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

Video Face Swap

Video Face Swap

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

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)

BinaryX is renamed FORM again, and the FOUR it gives to the community is about to soar? BinaryX is renamed FORM again, and the FOUR it gives to the community is about to soar? Mar 04, 2025 pm 12:00 PM

BinaryX's token name change: from BNX to FOUR, and then to FORM, the deep meaning behind strategic adjustments BinaryX recently changed the token symbol from $FOUR to $FORM, which has attracted widespread attention from the industry. This is not the first time BinaryX has changed its name, and its token symbol has undergone a transition from BNX to FOUR. This article will explore in-depth the strategic intentions behind this series of name change. 1. Token name change process and strategic considerations BinaryX initially launched the $BNX token based on the BNB chain in 2021 to support its Play-to-Earn (P2E) gaming ecosystem. In early 2024, in order to optimize the economic model, BinaryX divided $BNX and gradually expanded to GameF

Can there be multiple forms in html5? Can there be multiple forms in html5? Aug 01, 2022 pm 05:28 PM

There can be multiple forms in html5. The rules allow multiple form tags to be used in the same HTML page. However, in order to prevent the backend from not recognizing it when submitting, you need to add different IDs or classes to the form. The syntax is "<from action="url" id=" id value 1">Form element</from><from action="url" id="id value 2">Form element</from>.....".

Can the create statement be used to create a table structure and append new records? Can the create statement be used to create a table structure and append new records? Jul 25, 2022 am 11:25 AM

cannot. The function of the CREATE statement is to create a table structure, but it cannot append new records. You can use the INSERT statement to append new records. The CREATE statement can be used to create a new table in the database and specify the attributes and constraints of the data columns; however, the newly created table is an empty table and requires the use of the INSERT statement to append new records. The INSERT statement is used to insert one or more rows of tuple data into an existing table in the database.

What is the tag that defines the form in html5 What is the tag that defines the form in html5 Jul 26, 2022 pm 04:26 PM

The tag defining a form in HTML5 is "<form>". The form tag is used to create an HTML form (form field) for user input to collect and transfer user information. All content in the form will be submitted to the server; the syntax "<form action="Submit Address" method="Submit Method " name="form name">form control</form>". A form can contain one or more form elements, such as input, select, and textarea.

Comprehensively organize elements related to form forms! Comprehensively organize elements related to form forms! Aug 05, 2022 am 11:45 AM

This article gives you a detailed summary of the knowledge points related to form elements in HTML. I hope it will be helpful to you!

What should I do if I get an error in creat react app? What should I do if I get an error in creat react app? Dec 27, 2022 am 11:29 AM

Solution to create react app error: 1. Switch the Taobao mirror source through "npm config set registry https://registry.npm.taobao.org"; 2. By executing "E:\workspace\demo\p4>npx create- react-app todolist" command to reinstall it.

What should I do if the form cannot be submitted to php? What should I do if the form cannot be submitted to php? Dec 01, 2022 am 09:08 AM

Solution to form form cannot be submitted to PHP: 1. Open the corresponding code file; 2. Modify the "onload="javascript:document.form1.submit();" statement; 3. Change the name of submit.

php记录搜索引擎蜘蛛爬行记录代码 php记录搜索引擎蜘蛛爬行记录代码 Jun 13, 2016 am 10:08 AM

php记录搜索引擎蜘蛛爬行记录代码。php教程记录搜索引擎蜘蛛爬行记录代码 center form action=setup.php method=post table align=center tr td服务器:/tdtdinput value=localhost name=server //td /tr tr td用

See all articles