app/Article.php
namespace App; use Illuminate\Database\Eloquent\Model; class Article extends Model { //对应的表 protected $table = 'articles'; //通过model可以写入的字段 protected $fillable = [ 'title', 'content', ]; }
4、存储逻辑代码
打开 ArticlesController.php 控制器,找到 store() 方法。
app/Http/Controllers/ArticlesController.php
public function store(Request $request) { //数据验证 错误处理 $this->validate($request,[ 'title'=>'required|max:50', 'content'=>'required|max:500', ]); // 1 orm方式写入 $article = Article::create([ 'title'=>$request->title, 'content'=>$request->content, ]); //2 或者 /* $article = new Article(); $article->title =$request->title; $article->content = $request->content; $article->save();*/ //3 db方式写入 //insert()方法返回值为true 和 false //$res = DB::table('articles')->insert(['title'=>$request->title,'content'=>$request->content]); return redirect()->route('blog.index'); }
验证错误显示
@if (count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif
七、文章列表展示
完成了添加文章功能后,就可以实现我们的文章列表展示页了。
打开 ArticlesController.php 找到 index()
方法,添加代码如下:
app/Http/Controllers/ArticlesController.php
use App\Article; public function index() { $articles = Article::orderBy('created_at','asc')->get(); return view('articles.index', ['articles'=>$articles]); }
视图index.blade.php
@extends('layouts.art') @section('content') <a class="btn btn-primary" href="{{route('blog.create')}}" rel="external nofollow" >添加文章</a> @foreach($articles as $article) <div class="panel panel-default"> <div class="panel-body"> {{$article->title}} <a href="{{route('blog.show',$article->id)}}" rel="external nofollow" class="btn btn-info">阅读</a> <a href="{{route('blog.edit', $article->id)}}" rel="external nofollow" class="btn btn-info">修改</a> <form action="{{ route('blog.destroy', $article->id) }}" method="post" style="display: inline-block;"> {{ csrf_field() }} {{ method_field('DELETE') }} <button type="submit" class="btn btn-danger">删除</button> </form> </div> </div> @endforeach {!! $articles->render() !!} @endsection
八、编辑文章表单
编辑文章表单其实和之前创建的新建文章表单很类似,只是需要额外将现有的数据读取出来填在表单上。
首先我们在文章列表页的每个文章上添加一个编辑按钮:
视图:
@extends('layouts.art') @section('content') <form class="form-horizontal" method="post" action="{{route('blog.update',$article->id)}}"> {{ csrf_field() }} {{ method_field('PATCH') }} <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">标题</label> <div class="col-sm-10"> <input type="title" class="form-control" id="title" name="title" value="{{ $article->title }}"> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">内容</label> <div class="col-sm-10"> <textarea class="form-control" rows="5" id="content" name="content"> {{ $article->content }}</textarea> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">修改</button> </div> </div> </form> @endsection