laravel 博客(resource)
阿新 • • 發佈:2018-08-11
public source let 路由 inpu 增刪 com 通過 NPU
laravel的資源路由極大的方便了數據庫的增刪改查
1、創建資源路由
Route::resource(‘article‘,‘ArticleController‘);
2、查看。創建好資源路由後,通過artisan命令創建控制器。
php artisan make:controller ArticleController; php artsian route:list //查看資源路由列表,如圖所示
分析一下上面的路由;
①、get方法直接訪問admin/article,可以直接訪問ArticleController@index; 用於頁面的顯示,直接提取數據庫顯示在頁面
public function index(){ $data = Article::orderBy(‘art_id‘,‘desc‘)->paginate(5); return view(‘admin.article.index‘,compact(‘data‘)); }
②、post方法訪問admin/article,訪問的是ArticleController@store; 用於數據的添加;(需要csrf認證)
public function store(){ $input = Input::except(‘_token‘);$input[‘art_time‘] = time(); $rules = [ ‘art_title‘ =>‘required‘, ‘art_content‘ =>‘required‘, ]; $message = [ ‘art_title.required‘=>‘文章標題必須填寫‘, ‘art_content.required‘ =>‘文章內容必須填寫‘ ]; $validator = Validator::make($input,$rules,$message); if($validator->passes()){ $re = Article::create($input); if($re){ return redirect(‘admin/article‘); }else{ return view(‘admin/article/create‘)->with(‘error‘,‘添加數據失敗‘); } }else{ return back()->withErrors($validator); } }
③、get方式訪問admin/article/create,訪問的是ArticleController@create;用於的添加數據的顯示;
public function create(){ $cate = Category::tree(); return view(‘admin.article.add‘,compact(‘cate‘)); }
④、delete方式訪問admin/article/{參數},訪問的是ArticleController@destroy;用於數據的刪除;(需要csrf認證)
表單提交是需要表明提交方法:
<input type="hidden" name="_method" value="delete">
public function destroy($art_id){ $re = Article::where(‘art_id‘,$art_id)->delete(); if($re){ $data = [ ‘status‘=>‘0‘, ‘msg‘ =>‘文章刪除成功‘ ]; }else{ $data = [ ‘status‘=>‘1‘, ‘msg‘ =>‘文章刪除失敗,稍後重試‘ ]; } return $data; }
⑤、put方式提交admin/article/{article};訪問的是ArticleController@update,用於更新數據;(需要csrf認證)
<input type="hidden" name="_method" value="put"> public function update($art_id){ $input = Input::except(‘_token‘,‘_method‘); $input[‘art_time‘] = time(); $re = Article::where(‘art_id‘,$art_id)->update($input); if($re){ return redirect(‘admin/article‘); }else{ return back()->with(‘error‘,‘文章更新數據失敗‘); } }
⑥、get訪問admin/article/{article};訪問的是ArticleController@show,用於單條數據的顯示;
public function index($id){ $data = Article::orderBy(‘art_id‘,$id)->get(5); return view(‘admin.article.show‘,compact(‘data‘)); }
⑦、get方式訪問admin/article/{article}/edit;訪問的是ArticleController@edit,用於修改數據的顯示;
public function edit($art_id){ $field = Article::find($art_id); $cate = Category::tree(); return view(‘admin.article.edit‘,compact(‘field‘,‘cate‘)); }
3、通過資源路可以直接訪問以上地址,方便的數據的管理。
laravel 博客(resource)