文章类型CRUD
1. 生成数据库
1.1 创建数据库迁移文件
php artisan make:migration create_post_types_table
1.2 运行数据库迁移
php artisan migrate
2. 创建模型
php artisan make:model Post_Type
创建模型注意事项
- 表名为复数形式,模型名称为单数形式
- 表名如果是多个单词组成,且中间有下划线,如post_types,则模型名称使用单数形式,且每个单词首字母大写,并去除下划线,如PostType
3. 创建控制器
一般一个功能模块对应一个控制器
php artisan make:controller PostTypeController
4. 配置路由
打开项目根目录下的 routes 目录下的 web.php 文件,配置路由
5. 展示列表信息
// 展示文章类型列表信息
public function index()
{
$types=PostType::all();
return view('posttype/index',['$types'=>$types]);
}
在 resouces/views 目录下,创建 posttype 目录,然后在其中创建 index.blade.php
index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<a href="/post_types/add">添加类型</a>
<h2>文章列表</h2>
<table class="table">
<tr>
<th>类型编号</th>
<th>类型名称</th>
<th>创建时间</th>
<th>操作</th>
</tr>
@foreach($types as $item)
<tr>
<td>{{$item->id}}</td>
<td>{{$item->title}}</td>
<td>{{$item->created_at}}</td>
<td>
<a href="/post_types/{{$item->id}}/edite" class="btn btn-info">编辑</a>
<a href="/post_types/{{$item->id}}/delete" class="btn btn-danger">删除</a>
</td>
</tr>
@endforeach
</table>
</div>
</body>
</html>
6. 增加
展示增加页面
add.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style>
.box{
margin-top: 100px;
}
</style>
</head>
<body>
<div class="container box">
<form action="/post_types" method="post" class="form-horizontal">
{{csrf_field()}}
<div class="form-group">
<label for="title" class="col-sm-2 control-label">类型名称</label>
<div class="col-sm-10">
<input type="text" name="title" id="title" class="form-control">
</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>
</div>
</body>
</html>
PostTypeController 控制器中加入 store 方法
//新增数据
public function store(){
// dd(request()->all());
$model=new PostType();
$model->title=request('title');
$res=$model->save();
if($res){
return redirect('/post_types');
}else{
return redirect('/post_types/add');
}
}