Laravel实现文章分类的显示,添加,更新与删除

01.创建文章分类表

创建category表

'CREATE TABLE `dr_category` (
  `cate_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `cate_name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `cate_title` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `cate_keyword` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `cate_description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `cate_view` int(10) unsigned NOT NULL DEFAULT ''0'',
  `cate_order` tinyint(3) unsigned NOT NULL DEFAULT ''0'',
  `cate_pid` int(10) unsigned NOT NULL DEFAULT ''0'',
  PRIMARY KEY (`cate_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci'

使用migrate命令创建表

public function up()
    {
      Schema::dropIfExists('category');
      Schema::create('category', function (Blueprint $table) {
          $table->increments('cate_id');
          $table->string('cate_name', 100);
          $table->string('cate_title', 255)->nullable();
          $table->string('cate_keyword', 255)->nullable();
          $table->string('cate_description', 255)->nullable();
          $table->unsignedInteger('cate_view')->default(0);
          $table->unsignedTinyInteger('cate_order')->default(0);
          $table->unsignedInteger('cate_pid')->default(0);
      });
    }

02.创建Seeder文件

A.创建命令
php artisan make:seeder CategoryTableSeeder
B.编写Seeder文件并赋值

public function run()
    {
        DB::table('category')->insert(array(
            array(
              'name'=>'时尚',
            ),
            array(
              'name'=>'旅游',
            ),
            array(
              'name'=>'美食',
            ),
            array(
              'name'=>'健身',
            ),
            array(
              'name'=>'二次元',
            ),
          )
        );
    }

C.执行Seeder文件
php artisan db:seed --class=CategoryTableSeeder

03.使用遍历的方法实现二级分类的显示

/**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $categories = Category::all();
        $data = $this->getTree($categories,'cate_name','cate_id','cate_pid',0);
        return view('admin.category.index',['cate'=>'category','data'=>$data]);
    }

    // 二级分类,也可以使用递归方法实现
    public function getTree($data,$column_name,$id='id',$pid='pid',$defaultRootId=0){
      $arr = array();
      foreach ($data as $pval) {
        if ($pval->$pid==$defaultRootId) {
        $pval['_'.$column_name]=$pval[$column_name];
          $arr[]=$pval;
          foreach ($data as $val) {
            if ($val->$pid==$pval->$id) {
              $val['_'.$column_name]='├── '.$val[$column_name];
              $arr[]=$val;
            }
          }
        }
      }
      return $arr;
    }

04.分类的创建

使用create方法,显示表单页面;使用store提交到数据库存储;
create方法与前端模板

public function create()
    {
      $pcategories = Category::where('cate_pid',0)->get();
      return view('admin.category.create',['cate'=>'category','pcategories'=>$pcategories]);
    }
  <div class="card card-small mb-3">
          <div class="card-body">
            <form class="add-category" action="{{ url('admin/category') }}" method="post" name="add-category">
              {{ csrf_field() }}
              <input type="text" name="cate_name" class="form-control form-control-lg col-md-6 mb-3" placeholder="分类名" value="">
              <input type="text" name="cate_order" class="form-control form-control-lg col-md-6 mb-3" placeholder="排序" value="">
              <select name="cate_pid" class="form-control form-control-lg col-md-5 mb-3">
                <option selected value="">==顶级分类==</option>
                @foreach ($pcategories as  $value)
                  <option value="{{ $value->cate_id }}">{{ $value->cate_name }}</option>
                @endforeach
              </select>
              <textarea name="cate_title" class="form-control form-control-lg mb-3" rows="8" cols="80" placeholder="分类描述" ></textarea>
              <input type="text" name="cate_keyword" class="form-control form-control-lg mb-3" placeholder="SEO关键字" value="">
              <textarea name="cate_description" class="form-control form-control-lg mb-3" rows="8" cols="80" placeholder="SEO描述" ></textarea>
        
            </form>
          </div>
        </div>
  <button class="btn btn-sm btn-accent" onclick = "createCate()">
 <i class="material-icons">file_copy</i> Publish</button>
<script type="text/javascript">
// 提交使用的是createCate()提交
function createCate(){
  document.forms['add-category'].submit();
}
</script>

05.更新分类

控制器

public function edit($id)
    {
        $pcategories = Category::where('cate_pid',0)->get();
        $category = Category::find($id);
        return view('admin.category.edit',['cate'=>'category','category'=>$category,'pcategories'=>$pcategories]);
    }
public function update($cate_id)
    {
        $input = Input::except('_token','_method');
        $res = Category::where('cate_id',$cate_id)->update($input);
        if ($res) {
          return redirect('admin/category');
        }else{
          return back()->withErrors('更新分类失败!');
        }
    }

html模板

<form class="add-category" action="{{ route('category.update',$category) }}" method="post" name="add-category">
              @method('PUT')
              {{ csrf_field() }}
              <input type="text" name="cate_name" class="form-control form-control-lg col-md-6 mb-3" placeholder="分类名" value="{{ $category->cate_name }}">
              <input type="text" name="cate_order" class="form-control form-control-lg col-md-6 mb-3" placeholder="排序" value="{{ $category->cate_order }}">
              <select name="cate_pid" class="form-control form-control-lg col-md-5 mb-3">
                <option selected value="">==顶级分类==</option>
                @foreach ($pcategories as  $value)
                  <option value="{{ $value->cate_id }}" {{ $category->cate_pid==$value->cate_id?'selected':'' }}>{{ $value->cate_name }}</option>
                @endforeach
              </select>
              <textarea name="cate_title" class="form-control form-control-lg mb-3" rows="8" cols="80" placeholder="分类描述" >{{ $category->cate_title }}</textarea>
              <input type="text" name="cate_keyword" class="form-control form-control-lg mb-3" placeholder="SEO关键字" value="{{ $category->cate_keyword }}">
              <textarea name="cate_description" class="form-control form-control-lg mb-3" rows="8" cols="80" placeholder="SEO描述" >{{ $category->cate_description }}</textarea>
            </form>

06.删除分类

判断分类中是否存在子分类,存在不能删除;
不存在时,进行分类删除操作

public function destroy($id)
    {
        // 判断是否为有子分类
        if(Category::where('cate_pid',$id)->exists()) {
          $data = [
            'status' =>2,
            'msg'=>'请先删除当前分类下的所有子分类后重试!'
          ];
        }else{
          if(Category::where('cate_id',$id)->delete()){
            $data = [
              'status' => 0,
              'msg' => "分类删除成功!",
            ];
          }else{
            $data = [
              'status' => 1,
              'msg' => "分类删除失败,请稍后重试!",
            ];
          }
        }
        return $data;
    }

前端采用POST方法异步传输,成功删除后显示提示信息,并刷新页面,具体代码:

<a href="javascript:;" onclick="deleteOrder({{ $category->cate_id }})">删除</a>
<script type="text/javascript">
  // 删除方法
  function deleteOrder(cate_id){
    layer.confirm('您确认删除该分类吗', {
      btn: ['确认','取消'] //按钮
    }, function(){
      $.post("{{ url('admin/category/') }}/"+cate_id,{'_method':'delete','_token':"{{ csrf_token() }}"},function(data){
        if (data.status==0) {
          layer.msg(data.msg, {icon: 6,time: 1500},function(){
            location.href = location.href;
          });
        } else {
          layer.msg(data.msg, {icon: 5});
        }
      });
    });
  }

</script>
posted @ 2019-08-14 18:15  cicarius  阅读(594)  评论(0编辑  收藏  举报