Laravel5 series tutorial 6: Form Forms

Source: Internet
Author: User
Tags form post
Laravel5 series tutorial 6: Form Forms

From: https://jellybool.com/post/programming-with-laravel-5-laravel-forms-input

Before we start, we will beautify the interface a little bit first:

First to begin:

1. app.blade.php2. articles/index.blade.php3. articles/show.blade.php

If you are lazy, you can use ctrl + c to modify the following view code.

In app. blade. php: replace the original @ yield ('content') code with the following code:

    

@yield('content')

Add a p and a section to the table.

Introduce these two css files:

 
 

One is bootstrap and the other is custom.

In the articles/index. blade. php file, we place each $ article in the tag:

@ Foreach ($ articles as $ article) id }}" >{{ $ article-> title }}

{{$ Article-> intro }}

Id }}">More

@ Endforeach

Then, modify the articles/show. blade. php view file:

@section('content')                        id }}" rel="bookmark"> {{ $article->title }}                

{{ $article->content }}

@endsection

Finally, let's look at the effect:

At the end of the tutorial, you can basically complete a small product that is the same as your blog.

OK. after a little beautification, we can enter our topic: Use Forms in Laravel.

Prelude

Since we need to create an article, we first need to display the page for this article creation, just like the SF article writing page: http://segmentfault.com/write

So we need to repeat the content of the previous article:

Register a route and add the following in routes. php:

Route::get('article/create','ArticleController@create');

We specify article/create to load the create () method of ArticleController, and then we create it in ArticleController:

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

This create () method directly loads our create. blade. php, so we create this view file and create it in the previous views/articles/folder. blade. php:

@ Extends ('app') @ section ('content') write a new article @ endsection

Try http://blog.dev/article/create:

After loading everything correctly, we started to use our Forms, because when creating an article, we needed to submit the form before we could receive the content, in other words, almost every web application is inseparable from forms. even a registration or login page requires forms. as long as you need to collect user information or want to have UGC, forms are also inseparable. So let's start using Laravel Forms.

Use illuminate/html

Here we use an official Package: https://github.com/illuminate/html

We use composer to install it:

composer require illuminate/html

Wait for a while. after the installation is successful, how can we tell Laravel that the Package has been installed? Or how can we combine this Package with the entire Laravel system?

By providing the Service Provider and specifying the Facade! In this way, it can be perfectly integrated with Laravel.

Why is Service Provider and Facade directly called? Because I know how to translate these two documents.

By the way, many PHP composer packages have different versions of each framework. for example, HtmlPurifier filters html and prevents xss packages, this Laravel version is available:
Https://github.com/mewebstudio/Purifier, more or less, some good package will have Laravel version.

Configuration

Back to Service Provider and Facade, you may be confused about the concept of Service Provider at the beginning, but you do not need to worry about it now, even though you can open the config/app. php file to have a look:

'providers' => [            Illuminate\Foundation\Providers\ArtisanServiceProvider::class,            Illuminate\Auth\AuthServiceProvider::class,            Illuminate\Broadcasting\BroadcastServiceProvider::class,            //...            ]

You will see that the providers array contains a bunch of pre-configured Service providers in Laravel. for example, Auth and Controller can be found here. If you pull down, you will see an array like this:

'aliases' => [    'App'       => Illuminate\Support\Facades\App::class,    'Artisan'   => Illuminate\Support\Facades\Artisan::class,    'Auth'      => Illuminate\Support\Facades\Auth::class,    //...    ]

Aliases is actually a shortcut. Once a shortcut is specified here, we can use it globally in Laravel. for example, I use Auth in code, in fact, I am using Illuminate \ Support \ Facades \ Auth: class, and then going deeper. we are actually using Illuminate \ Auth \ AuthServiceProvider: class in providers.

Illuminate/html has been downloaded while writing the above:

Then, configure our illuminate/html according to the above method, and add our Service Provider in providers in config/app. php:

Illuminate\Html\HtmlServiceProvider::class,

The configuration length is as follows:

OK. after the Service Provider is added, we will add our Facade, that is, after the value of aliases:

'Form'      => Illuminate\Html\FormFacade::class,

After configuration, check the image length as follows:

Use Forms

After these two configurations are complete, we can use them in our create. blade. php view:

@ Section ('content') write new article {!! Form: open ()!!} {!! Form: close ()!!} @ Endsection

We added two lines {!! Form: open ()!!} And {!! Form: close ()!!}, For {!! For a similar symbol, please use a class such as the blade {, so you don't have to worry too much about this. Visit http://blog.dev/article/createtest:

At first glance, there seems to be no change, but when you want to view the page source code or use the developer tool to check the element, you can find that the form element has been created.

It is not difficult to find that Laravel's Form also generates a hidden Form (name = "_ token") by default, which is a bit of security support for Form submission by Laravel by default. When the form is submitted, Laravel automatically checks whether the _ token is consistent with the _ token saved in the session. if the _ token is inconsistent, it will jump back to the remote page directly, data cannot be submitted.

Since the Form can be used normally, we can create the Form we need:

{!! Form: open ()!!}

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

{!! Form: label ('content', 'body :')!!} {!! Form: textarea ('content', null, ['class' => 'form-control'])!}

{!! Form: submit ('post analytics', ['class' => 'btn btn-success form-control'])!}

{!! Form: close ()!!}

We are {!! Form: open ()!!} To add something, let's take a look at our results:

The following is a detailed explanation:

{!! Form::text('title',null,['class'=>'form-control']) !!}

Use this to open the knife:

  • Form: textAnd a bunchYou can refer to this document.

  • 'Title' indicates name = 'title'

  • Null indicates value =''

  • 'Class' => 'form-control' indicates class = 'form-control'. you can specify the id, placeholder, and other attributes you want to specify.

  • However, when Form: open () does not specify the submission path, it is submitted to this page by default, which is not good for us to clearly define the division of labor, this page is used to load views. for the content submitted by the form, we hope to use another method for processing. so let's write it.

    First, specify the url submitted by the Form in Form: open (), and add the url directly in:

    {!! Form::open(['url'=>'article/store']) !!}

    We specify that the form post is submitted to the article/store address, and then register the route address in routes. php:

    Route::post('article/store','ArticleController@store');

    Note that we use Route: post instead of Route: get, which is used to receivePost. Then, complete the settings and create the store () method in ArticleController:

    public function store()    {        $input = Request::all();        return $input;    }

    In this method, we introduce the Request that comes with Laravel and use Request: all () to obtain the content submitted by all users (_ token, name is very content), if you want to obtain the content of a specific form input, you can use Request: get (), such as Request: get ('title '), return directly to see what the user has entered. let's try:

    Create a new article

    OK. after successfully obtaining the submitted content, we need to save the content to the database. how can this problem be achieved? In the fourth article, we mentioned the Eloquent's create () method can be used now, so we can write it as follows:

    Article::create($input);

    Laravel automatically filters the submitted content of _ token.

    However, after an article is created, we do not want to return $ input, but to jump to a page, such as our homepage, we need to see whether it is successfully qualified in the article list, so let's write:

    public function store()    {        $input = Request::all();        Article::create($input);        return redirect('/');    }

    We directly use Laravel's redirect () function to jump to the homepage. At this time, we can implement our logic with just three lines of code, so let's try:

    Seems to have succeeded? However, we think this sorting is a bit problematic. the newly created article is of course at the top, so we can modify it in the index () method of ArticleController:

    public function index()    {        $articles = Article::latest()->get();        return view('articles.index',compact('articles'));    }

    Replace the original all () with latest ()-> get (), refresh,

    We found that the latest article intro was blank. let's look at the database:

    We found that the intro of the created article is null, and published_at is 0000-00-00 00:00:00. this is not what we want. why? Because we didn't have the two data when we submitted it. to solve this problem, we can use Article: create ($ input) previously configured, for example:

    Public function store () {$ input = Request: all (); // add two rows below. Take a look at the Request :: use $ input ['Intro'] = mb_substr (Request: get ('content'),) for get; $ input ['hhed _ at'] = Carbon :: now (); Article: create ($ input); return redirect ('/');}

    For the intro field, the first 64 content fields are taken, and published_at is the default creation time. Currently, the code is a bit violent, but it is a solution. we will make the code much cleaner later. Let's try again:

    Bang, succeeded. let's look at the database:

    At this point, the basic process for creating an article is complete, but there is another problem here. if you try to submit data directly on the page created by the article without filling in anything, you can check what will happen. if you are not sure, you can check what happened to your database.

    Next section

    In view of the final problem and the content of the form involved, the next section seems to be a logical unit. it should be said that form verification, in Laravel, is Request Validation.

    Finally,

    Happy Hacking

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.