Create a RESTFul controller for laravel routing to add, delete, modify, and query articles.

Source: Internet
Author: User
Tags documentation trim

The basic controller, controller routing, and controller middleware are relatively simple. We will not repeat them here. For more information, see The HTTP controller documentation.

1. Create a RESTFul controller
Note: for details about the RESTFul style and its specifications, refer to this article: Understanding the RESTful architecture.
In this article, we will mainly discuss how to create a RESTFul controller for adding, deleting, modifying, and querying blog articles. It is very easy to create such a controller. Just run the following Artisan command in the application root directory:

Php artisan make: controller PostController
This command generates a PostController. Php file in the app/Http/Controllers Directory. The controller content is as follows:

<? Php

Namespace App \ Http \ Controllers;

Use Illuminate \ Http \ Request;

Use App \ Http \ Requests;
Use App \ Http \ Controllers \ Controller;

Class PostController extends Controller
    {
/**
* Displays the document list.
         *
* @ Return Response
*/
Public function index ()
        {
//
        }

/**
* Create a new article form page
         *
* @ Return Response
*/
Public function create ()
        {
//
        }

/**
* Store the newly created article to the memory
         *
* @ Param Request $ request
* @ Return Response
*/
Public function store (Request $ request)
        {
//
        }

/**
* Display the specified article
         *
* @ Param int $ id
* @ Return Response
*/
Public function show ($ id)
        {
//
        }

/**
* Display the form page for editing a specified article
         *
* @ Param int $ id
* @ Return Response
*/
Public function edit ($ id)
        {
//
        }

/**
* Update a specified article in the memory
         *
* @ Param Request $ request
* @ Param int $ id
* @ Return Response
*/
Public function update (Request $ request, $ id)
        {
//
        }

/**
* Remove a specified article from the memory
         *
* @ Param int $ id
* @ Return Response
*/
Public function destroy ($ id)
        {
//
        }
    }
2. Register a route for a RESTFul controller
Next we will register the route for the controller in the routes. Php file:

Route: resource ('post', 'postcontroller ');
This route contains sub-routes pointing to multiple actions:

Method path action route name
GET/post index post. index
GET/post/create post. create
POST/post store post. store
GET/post/{post} show post. show
GET/post/{post}/edit post. edit
PUT/PATCH/post/{post} update post. update
DELETE/post/{post} destroy post. destroy
For example, if we access the http://laravel.app: 8000/post in the browser in the GET Way, the access is the PostController index method, we can generate the corresponding routing URL through route ('post. Index. Similarly, if we access http://laravel.app: 8000/POST in post mode, the access is the PostController's store method, the corresponding POST form action attribute value can be through route ('post. store.

3. Instance tutorial-add, delete, modify, and query an article
Next we will demonstrate the basic addition, deletion, modification, and query operations. We will talk about database operations later. Here we use cache as the storage (Laravel uses file cache by default ).

Note: the Cache facade is used here. Do not forget to use the use Cache on the top of PostController before use. For more information about Cache usage, see the Cache documentation.
3.1 add an article

First, we will add an article to define the create method and store method of the PostController controller as follows (we will talk about the view Department later and put the HTML in the PHP variable here ):

/**
* Create a new article form page
*
* @ Return Response
*/
Public function create ()
{
$ PostUrl = route ('post. Store ');
$ Csrf_field = csrf_field ();
$ Html = <CREATE
<Form action = "$ postUrl" method = "POST">
$ Csrf_field
<Input type = "text" name = "title"> <br/>
<Textarea name = "content" cols = "50" rows = "5"> </textarea> <br/>
<Input type = "submit" value = "submit"/>
</Form>
CREATE;
Return $ html;
}

/**
* Store the newly created article to the memory
*
* @ Param Request $ request
* @ Return Response
*/
Public function store (Request $ request)
{
$ Title = $ request-> input ('title ');
$ Content = $ request-> input ('content ');
$ Post = ['title' => trim ($ title), 'content' => trim ($ content)];

$ Posts = Cache: get ('posts', []);
   
If (! Cache: get ('post _ id ')){
Cache: add ('post _ id', 1, 60 );
} Else {
Cache: increment ('post _ id', 1 );
    }
$ Posts [Cache: get ('post _ id')] = $ post;

Cache: put ('posts', $ posts, 60 );
Return redirect ()-> route ('post. Show', ['post' => Cache: get ('post _ id')]);
}
3.2 view articles

Visit the http://laravel.app: 8000/post/create page, fill in the form, click submit, save successfully, the page jumps to the details page:

/**
* Display the specified article
*
* @ Param int $ id
* @ Return Response
*/
Public function show ($ id)
{
$ Posts = Cache: get ('posts', []);
If (! $ Posts |! $ Posts [$ id])
Exit ('Nothing Found! ');
$ Post = $ posts [$ id];

$ EditUrl = route ('post. Edit', ['post' => $ id]);
$ Html = <DETAIL
<H3 >{$ post ['title']} <P >{$ post ['content']} </p>
<P>
<A href = "{$ editUrl}"> edit </a>
</P>
DETAIL;

Return $ html;
}
3.3 edit an article

Similarly, we define the edit method and update method for editing an article as follows:

/**
* Display the form page for editing a specified article
*
* @ Param int $ id
* @ Return Response
*/
Public function edit ($ id)
{
$ Posts = Cache: get ('posts', []);
If (! $ Posts |! $ Posts [$ id])
Exit ('Nothing Found! ');
$ Post = $ posts [$ id];

$ PostUrl = route ('post. Update', ['post' => $ id]);
$ Csrf_field = csrf_field ();
$ Html = <UPDATE
<Form action = "$ postUrl" method = "POST">
$ Csrf_field
<Input type = "hidden" name = "_ method" value = "PUT"/>
<Input type = "text" name = "title" value = "{$ post ['title']}"> <br/>
<Textarea name = "content" cols = "50" rows = "5" >{$ post ['content'] }</textarea> <br/>
<Input type = "submit" value = "submit"/>
</Form>
UPDATE;
Return $ html;

}

/**
* Update a specified article in the memory
*
* @ Param Request $ request
* @ Param int $ id
* @ Return Response
*/
Public function update (Request $ request, $ id)
{
$ Posts = Cache: get ('posts', []);
If (! $ Posts |! $ Posts [$ id])
Exit ('Nothing Found! ');

$ Title = $ request-> input ('title ');
$ Content = $ request-> input ('content ');

$ Posts [$ id] ['title'] = trim ($ title );
$ Posts [$ id] ['content'] = trim ($ content );

Cache: put ('posts', $ posts, 60 );
Return redirect ()-> route ('post. Show', ['post' => Cache: get ('post _ id')]);
}
3.4 delete an article

We can also use the destroy method to delete an article:

/**
* Remove a specified article from the memory
*
* @ Param int $ id
* @ Return Response
*/
Public function destroy ($ id)
{
$ Posts = Cache: get ('posts', []);
If (! $ Posts |! $ Posts [$ id])
Exit ('Nothing Deleted! ');

Unset ($ posts [$ id]);
Cache: decrement ('post _ id', 1 );

Return redirect ()-> route ('post. Index ');

}
To DELETE an article, you need to refer to the method used to edit the form forgery to DELETE a form (usually using AJAX to DELETE it), which is not demonstrated here.

3.5 Article list

Finally, let's define an index method for displaying the list of all articles:

/**
* Displays the document list.
*
* @ Return Response
*/
Public function index ()
{
$ Posts = Cache: get ('posts', []);
If (! $ Posts)
Exit ('Nothing ');

$ Html = '<ul> ';

Foreach ($ posts as $ key => $ post ){
$ Html. = '<li> <a href = '. route ('post. show ', ['post' => $ key]). '> '. $ post ['title']. '</li> ';
    }

$ Html. = '</ul> ';

Return $ html;
}

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.