Laravel5 basics (9)-form

Source: Internet
Author: User
: This article mainly introduces Laravel5 basics (9)-forms. For more information about PHP tutorials, see. First, let's modify the route to add an article release.

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

Then modify the controller

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

We return a view to create this view. Of course we can use HTML to create a form directly, but we have a better function. We use an open-source library, illuminate \ html developed by Jeffrey Way. Install the dependency Library:

composer require illuminate/html

The laravel library must be registered in laravel for use. Inconfig/app.php, We can see what laravel providesproviderField, which describes the laravel library function. InLaravel Framewirk Service Providers...Add the newly addedHtmlProvider

'Illuminate\Html\HtmlServiceProvider',

We do not want to useIlluminate\Html\FromFacadeFor such a long name, we need a short name. In the currentapp.phpFind the aliases segment and add the alias at the end.

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

OK. Now let's create a view,views/articles/create.blade.php

@ Extends ('layout ') @ section ('content') Write a New Article
  {-- Use the illuminate \ html open source library we added --}}{!! Form: open ()!!} {!! Form: close ()!!} @ Stop

Access/articles/createWhy? Let's test what went wrong. Make the following changes in the controller:

    public function show($id) {        dd('show');                $article = Article::findOrFail($id);        return view('articles.show', compact('article'));    }

You are not mistaken.showAdddd()Method, this method simply outputs a message and then dies. Visit again/articles/createWhat did you see, and you saw the outputshow.

Why do we accesscreateThe result is routed to us.show? Let's check what happened to the route.

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

The above is our route. Note thatarticles/{id}This means that this is a wildcard.articles/All the other things will match. do you know? Our/articles/createIt is also matched by him. OMG!

The solution is to adjust the order:

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

That is, you should always pay attention to this problem in route settings from special to normal. Now we are accessingarticles/createEverything is OK.

Check the source code in the browser and you will find that not onlymethodAndactionA hidden_tokenThe field is used as the server's verification of the form to avoid forgery attacks by hackers.

Let's modify our view and add fields:

@ Extends ('layout ') @ section ('content') Write a New Article
  {-- Use the illuminate \ html open source library we added --}}{!! Form: open ()!!}

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

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

{!! Form: submit ('add article', ['class' => 'btn btn-primary form-control'])!}

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

When a form is submittedpostMethod submissionarticles/createBut according to the RESTful habits, we hopepostTo/articlesTo modify the Form method of the view and set the submission path.

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

Then we process the form submission event in the route.

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

Let's process the controller.

// Note: delete the following use Statement. We use the Request // use App \ Http \ Requests \ Request in the facade interface; // introduce Requestuse Illuminate \ Support \ Facades \ Request; public function store () in the namespace below () {// use Illuminate \ Html \ Request to return all form input fields $ input = Request: all (); // we directly return $ input, return $ input ;}

We can directly see the json result of the input form. If you only needtitleField value, you can useRequest::get('titel').

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

Article::create($input);

It's so simple, it's so capricious

If you have not forgotten Mass Assignment, we have defined$fillableArray to define the fields that can be directly stored increateWhen filling.

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

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

Try adding a record. But don't forget. We also have a field calledpublished_at, Let's deal with it.

    public function store() {        $input = Request::all();        $input['published_at'] = Carbon::now();        Article::create($input);                return redirect('articles');    }

Add a new record in the test.

Another problem is that the newly added controller should be shown at the beginning. let's modify the following controller.

Public function index () {// Obtain the Article in reverse order // you can do this // $ articles = Article: orderBy ('hhed _ at', 'desc ') -> get (); // simple method. of course, there is also oldest () $ articles = Article: latest ('hhed _ at')-> get (); return view ('Articles. index', compact ('Articles '));}

The above introduces Laravel 5 Basic (9)-form, including some content, and hope to be helpful to friends who are interested in PHP tutorials.

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.