laravel框加-创建RESTFul风格控制器实现文章增删改查

62 篇文章 0 订阅
33 篇文章 0 订阅

一、创建控制器

php artisan make:controller PostController -r

该命令会创建控制器并创建基础方法

二、添加路由

Route::resource('post','PostController');

三、实例

<?php
/**
 * cache 基于门面缓冲进行增删改查修
 *
 */

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Cache;  //引用cache缓冲
class PostController extends Controller
{
    /**
     * 显示文章列表
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $url = route('post.create');
        $posts = Cache::get('posts', []);
        $csrf_field = csrf_field();
        $html = '<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
        <a href="' . $url . '">添加</a> <br/><br/>';
        if (!$posts) {
            return $html;
        }
        $html .= '<table border="1px" width="200px;">';
        foreach ($posts as $key => $post) {
            $editurl = route('post.edit', ['post' => $key]);
            $showurl = route('post.show', ['post' => $key]);
            $html .= '<tr><td>' . $key . '<td>';
            $html .= '<a href=' . $showurl . '>' . $post['title'] . '</a></td>';
            $html .= '<td><a href="' . $editurl . '">编辑</a></td>';
            $html .= '<td><a href="javascript:;" οnclick="ajax(' . $key . ');">删除</a></td></tr>';
        }

        $html .= '</table>';
        $html .= <<<AJAX
        $csrf_field
        <script type="text/javascript">
            function ajax(id){
                 alert(id);
                 $.ajax({
                     type:   'POST',
                     url:    '/post/' + id,
                     data:   {'_method': 'delete','_token':$('input[name="_token"]').val()},
                     success: function(data){
                         console.log(data);
                         if(data.code ==0){
                             window.location.reload();
                         }
                     }
                 });
            }
        </script>
AJAX;

        return $html;
    }

    /**
     * 创建文章表单页面
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\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/><br/>
            内容:<textarea name="content" cols="50" rows="5"></textarea><br/><br/>
            <input type="submit" value="提交"/>
        </form>
CREATE;
        return $html;
    }

    /**
     * 文章保存
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\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')]);
    }

    /**
     * 显示指定文章
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\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']}</h3>
        <p>{$post['content']}</p>
        <p>
            <a href="{$editUrl}">编辑</a>
        </p>
DETAIL;
        return redirect()->route('post.index');
        return $html;
    }

    /**
     * 修改指定文章
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\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/><br/>
            内容:<textarea name="content" cols="50" rows="5">{$post['content']}</textarea><br/><br/>
            <input type="submit" value="提交"/>
        </form>
UPDATE;
        return $html;
    }

    /**
     * 更新指定文章
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\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')]);
    }

    /**
     * 删除指定文章
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        $posts = Cache::get('posts', []);
        if (!$posts || !$posts[$id])
            exit('Nothing Deleted');

        unset($posts[$id]);
        Cache::put('posts', $posts, 60);
        return ['code' => 0, '操作成功'];
    }
}
四、效果



本文为学习笔记,原内容请参考http://laravelacademy.org/post/549.html,如有侵权请通知博主删除。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值