Easy to take care of Laravel's curd operation. Simple message version (iv)

Source: Internet
Author: User
Tags php template

A: Objective to develop laravel simple message board

Two: routing Operation routes.php

<? PHP // get/msg/index Display message list//get/msg/add show form//post/msg/add accept POST data and inbound//get/msg/del/{id} Delete message//[get,post]/msg/up/{i D} Modify Message route::get (' Msg/index ', ' [email protected] '); Route:: Get (' msg/add ', ' [email protected] '); Route::p ost (' Msg/add ', ' [email protected] '); Route:: Get (' Msg/del/{id} ', ' [email protected] ')->where (' id ', ' \d+ '); Route:: Match ([' Get ', ' post '], ' msg/edit/{id} ', ' [email protected] ')->where (' id ', ' \d+ ');

Three: CMD window command to create user table

PHP Artisan make:migration create_table_msgs--create=msgs

Locate the resulting migration file and change it to:

<?PHP UseIlluminate\database\schema\blueprint; Useilluminate\database\migrations\migration;classCreatetablemsgsextendsmigration{/** * Run the migrations. * * @return void*/     Public functionUp () {Schema:: Create (' msgs ',function(Blueprint$table) {            $table->increments (' id '); $table-string(' title ', 30); $table->text (' content '); $table-timestamps ();    }); }    /** * Reverse the migrations. * * @return void*/     Public functionDown () {Schema::d rop (' msgs '); }}

cmd Window execution command:

PHP Artisan Migrate

This creates the table successfully.

Three: Increase the operation

First establish the msgcontroller.php controller, execute the command with the cmd window

PHP Artisan Make:controller Msgscontroller

Then the controller is automatically generated, and the resulting method is automatically generated to get the following controller:

Add Message:

Write the following method in msgcontroller.php:

Public function Add () {
Return view (' Msg.add ');
}

Create file msg, create template add.blade.php, special note, laravel with anti-station (CSRF) function, plus feature string can be {!! Csrf_field ()!!}

<! DOCTYPE html>

The browser address bar is entered as follows:

Ok,add The page has been created, then, after submitting the POST request will be addpost processing of the method, now create Addpost method under the controller below, of course, before the creation of MSG model,

Similarly, CMD window input command: PHP artisan make:model MSG

In Laravel (not mandatory), the table is called xxs, plural form.
If the user table is named users, the mail (email) table is called emails.
Class is related to the table name, and the generic table name removes S, which is the class name of the Model.
So:
The Model class of the users table is called Class User.
The Model class of the emails table is called Class E-mail, note the first letter capitalized.

 Public functionAddpost () {$msg=NewMSG (); $msg->title=$_post[' title ']; $msg->content=$_post[' Content ']; if($msg-Save ()) {            returnRedirect (' Msg/index '); }Else{            Echo' Add failed '; Exit(); }

OK, submit the page, processing success, the same can add a few more data, back to Msg/index, the next query out the content of the message

Four: Check out all the message content:

Create the index method under the controller, with the following code:

     Public function index () {        $msg=msg::get ();         return view (' Msg.index ', [' msg ' = +$msg])    ;

To create a index.blade.php template:

<! DOCTYPE html>        @foreach($msg   as $m)        <tr> <td>{{$m->title}}</td> <td>{{$m->content}}</td> <td> <a href= "/msg/del/{{$m->id}} "> Delete </a> <a href="/msg/edit/{{$m->id}} "> Edit </a> </td> </tr>        @Endforeach</table></body>

Enter the following in the browser address bar:

OK, that is so simple, then expand the knowledge of blade template (can skip directly, if necessary, look at):

In the blade template, instead of assign, it is passed in an array parameter set. Example: $data = [    ' title ' = ' Weather forecast ',    ' content ' = ' The weather is good today ',    ' score ' = Mt_rand (40,90),    ' users ' =>[' Zhangsan ', ' Lisi ', ' Wangwu ']];return view (' Test ', $data); @if (Express) # Note Express On both sides of the @elseif (Express) # expression shown in the @else@endif example: {{$score}} @if ($score >= 80) Excellent @elseif ($score >= 60) passed @else inferior @endif@for ($i =0; $i <10; $i + +)    {{$i}} <br> @endfor @foreach ($user as $u)    {{$u}} @endforeach @forelse ([] as $u) {{$u}}// If the array has data display data @emptynobody//If the array is empty, display @endforelse usage at a glance there are also public templates common, template inheritance, etc., self-learning is OK

Five: Create a Delete method under the controller, the code is as follows:

Public Function del ($id) {
$res =msg::find ($id)->delete ();
if ($res) {
Return redirect (' Msg/index ');
}else{
Echo ' delete failed ';
}
}

OK, delete successful

VI: Create a modification method under the controller

You first have to present the previous data to the template and then modify it:

Here's how:

 Public functionEdit (Request$request,$id){        if(Empty($_post)) {            $msg=msg::find ($id); returnView (' Msg.edit ', [' msg ' =$msg]); }Else{            $msg=msg::find ($id); $msg->title=$request-title; $msg->content=$request-content; $res=$msg-Save (); if($res) {           returnRedirect (' Msg/index '); }Else{            Echo' Update failed '; }        }    }

If you don't understand the request above, learn to understand it yourself, or change it in the following way:

 Public functionEdit$id){        if(Empty($_post)) {            $msg=msg::find ($id); returnView (' Msg.edit ', [' msg ' =$msg]); }Else{            $msg=msg::find ($id); $msg->title=$_post[' title ']; $msg->content=$_post[' Content ']; $res=$msg-Save (); if($res) {           returnRedirect (' Msg/index '); }Else{            Echo' Update failed '; }        }    }

Template Edit.blade.php page creation

<! DOCTYPE html>        {!! Csrf_field ()!! }        <p>             title : <input type= "text" name= "title" Value= "{{$msg->title}} ">        </p>        <p>             contents : <textarea name=" Content "id=" "cols=" "rows=" >{ {$msg->content}} </textarea>        </p>        <input type= "Submit" value= "Submission" >    </form></body> 

OK, to this simple message board is done!

Easy to take care of Laravel's curd operation. Simple message version (iv)

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.