后盾网lavarel视频项目---lavarel使用模型进行增删改查操作

一、总结

一句话总结:

使用模型操作常用方法

查一条:$model=Tag::find($id);
删一条:Tag::destroy($id);
查全部:$data=Tag::get();
增加:$model->create($request->all());

1、资源路由器操作处理的动作、URL、行为、路由名称?

看手册喽,修改和增加用的是两个,一个是get显示界面,一个是处理逻辑
动作 URI 行为 路由名称
GET /photos index photos.index
GET /photos/create create photos.create
POST /photos store photos.store
GET /photos/{photo} show photos.show
GET /photos/{photo}/edit edit photos.edit
PUT/PATCH /photos/{photo} update photos.update
DELETE /photos/{photo} destroy photos.destroy

2、更新操作中,需要表单传递PUT请求,如何做?

伪造表单方法:@method('PUT')
<form action="/foo/bar" method="POST">
@method('PUT')
</form>

3、解决剔除token字段存数据库的问题?

模型中定义$guarded为空数组:protected $guarded=[];

4、jquery自动传递csrf的token字段?

在页头创建csrf-token的meta标签,在页尾用ajaxSetup设置token的值
X-CSRF-TOKEN
除了检查 POST 参数中的 CSRF 令牌外, VerifyCsrfToken 中间件还会检查 X-CSRF-TOKEN 请求头。你应该将令牌保存在 HTML meta 标签中,如下: <meta name="csrf-token" content="{{ csrf_token() }}">
然后,一旦你创建了 meta 标签,就可以指示像 jQuery 这样的库自动将令牌添加到所有请求的头信息中。还可以为基于 AJAX 的应用提供简单、方便的 CSRF 保护。如下: $.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
{tip} 默认情况下,resources/assets/js/bootstrap.js 文件会用 Axios HTTP 函数库注册 csrf-token meta 标签中的值。如果不使用这个函数库,则需要为你的应用手动配置此行为。

二、lavarel使用模型进行增删改查操作

1、相关知识

资源控制器操作处理

动作 URI 行为 路由名称
GET /photos index photos.index
GET /photos/create create photos.create
POST /photos store photos.store
GET /photos/{photo} show photos.show
GET /photos/{photo}/edit edit photos.edit
PUT/PATCH /photos/{photo} update photos.update
DELETE /photos/{photo} destroy photos.destroy

指定资源模型

如果你使用了路由模型绑定,并且想在资源控制器的方法中使用类型提示,你可以在生成控制器的时候使用 --model选项:

php artisan make:controller PhotoController --resource --model=Photo

伪造表单方法

因为 HTML 表单不能生成 PUTPATCH 和 DELETE 请求,所以你需要添加一个隐藏的 _method 字段来伪造这些 HTTP 动作。 这个 Blade 指令 @method 可以为你创建这个字段:

<form action="/foo/bar" method="POST">
@method('PUT')
</form>
 

2、代码

一、控制器

app/Http/Controllers/Admin/TagController.php

 <?php

 namespace App\Http\Controllers\Admin;

 use App\Http\Requests\TagRequest;
use App\Model\Tag;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller; class TagController extends CommonController
{ /**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
session(['nowControllerAction'=>\App\Model\ControllerAndFunction::jointControllerAndFunction()]);
$data=Tag::get();
return view('admin.tag.index',compact('data'));
} /**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.tag.create');
} /**
* 保存新增的数据
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(TagRequest $request,Tag $model)
{
$model->create($request->all());
return redirect('/admin/tag');
//dd($request);
} /**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
} /**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$model=Tag::find($id);
return view('admin.tag.edit',compact('model'));
} /**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(TagRequest $request, $id)
{
$model=Tag::find($id);
$model['name']=$request['name'];
$model->save();
return redirect('/admin/tag');
} /**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Tag::destroy($id);
return response()->json(['message'=>'刪除成功','valid'=>1]);
}
}

第43行和第80行,都用TagRequest进行了验证

二、模型

app/Model/Tag.php

 <?php

 namespace App\Model;

 use Illuminate\Database\Eloquent\Model;

 class Tag extends Model
{
//$guarded表示不允许批量填充的字段
protected $guarded=[];
}

第10行,定义这个$guarded字段解决了剔除token字段存数据库的问题

Tag模型对应数据库tag表,控制器中就是用Tag进行数据库操作

三、请求

app/Http/Requests/TagRequest.php

 <?php

 namespace App\Http\Requests;

 use Illuminate\Foundation\Http\FormRequest;

 class TagRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
} /**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name'=>'sometimes|required',
];
} /**
* 中文提示
* @return array
*/
public function messages()
{
return [
'name.required'=>'标签名称不能为空',
];
}
}

四、视图

resources/views/admin/tag/create.blade.php
 @extends('admin.layout.master')
@section('title','新增标签')
@section('content')
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Dashboard
<small>Control panel</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
</ol>
</section> <!-- Main content -->
<section class="content">
<div style="padding-bottom:15px;">
<div class="btn-group" role="group" aria-label="...">
<a href="/admin/tag" type="button" class="btn btn-default">标签列表</a>
<a href="/admin/tag/create" type="button" class="btn btn-warning">新增标签</a>
</div>
</div> <div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">Horizontal Form</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form class="form-horizontal" action="/admin/tag" method="post">
{{csrf_field()}}
<div class="box-body">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">标签</label> <div class="col-sm-10">
<input type="text" name="name" class="form-control" id="name" required placeholder="标签">
</div>
</div> </div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-info">保存数据</button>
</div>
<!-- /.box-footer -->
</form>
</div> </section>
<!-- /.content -->
@endsection
resources/views/admin/tag/edit.blade.php
 @extends('admin.layout.master')
@section('title','修改标签')
@section('content')
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Dashboard
<small>Control panel</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
</ol>
</section> <!-- Main content -->
<section class="content">
<div style="padding-bottom:15px;">
<div class="btn-group" role="group" aria-label="...">
<a href="/admin/tag" type="button" class="btn btn-default">标签列表</a>
<a href="/admin/tag/create" type="button" class="btn btn-warning">修改标签</a>
</div>
</div> <div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">Horizontal Form</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form class="form-horizontal" action="/admin/tag/{{$model['id']}}" method="post">
{{csrf_field()}}
@method('PUT')
<div class="box-body">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">标签</label> <div class="col-sm-10">
<input type="text" name="name" class="form-control" id="name" required placeholder="标签" value="{{$model['name']}}">
</div>
</div> </div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-info">保存数据</button>
</div>
<!-- /.box-footer -->
</form>
</div> </section>
<!-- /.content -->
@endsection

第33行,请求伪造

resources/views/admin/tag/index.blade.php
 @extends('admin.layout.master')
@section('title','标签页面')
@section('content')
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Dashboard
<small>Control panel</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
</ol>
</section> <!-- Main content -->
<section class="content">
<div style="padding-bottom:15px;">
<div class="btn-group" role="group" aria-label="...">
<a href="/admin/tag" type="button" class="btn btn-warning">标签列表</a>
<a href="/admin/tag/create" type="button" class="btn btn-default">新增标签</a>
</div>
</div> <div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Bordered Table</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="table-responsive" style="overflow: visible;min-height: 200px;">
<table class="table table-hover">
<tbody>
<tr class="info">
<th style="width: 10px">#</th>
<th>标签</th>
<th>操作</th>
</tr>
@foreach($data as $d)
<tr>
<td>{{$d['id']}}.</td>
<td>{{$d['name']}}</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-info">操作</button>
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu" style="">
<li><a href="/admin/tag/{{$d['id']}}/edit">编辑</a></li>
<li><a href="javascript:;" onclick="del({{$d['id']}})">删除</a></li>
</ul>
</div>
</td>
</tr>
@endforeach </tbody>
</table>
</div> </div>
<!-- /.box-body -->
<div class="box-footer clearfix">
<ul class="pagination pagination-sm no-margin pull-right">
<li><a href="#">«</a></li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">»</a></li>
</ul>
</div>
</div> </section>
<!-- /.content -->
<script>
function del(id){
// require(['util'],function () {
// util.confirm('确定删除么?',function () {
//
// });
// });
if(confirm('确定删除么')){
$.ajax({
url:'/admin/tag/'+id,
method:'DELETE',
success:function (response) {
location.reload();
}
});
}
}
</script>
@endsection

这里的ajax没有传token字段是因为 模板主页里面进行了jquery的token验证,调用jquery会自动传token来验证的

 

后盾网lavarel视频项目---lavarel使用模型进行增删改查操作的更多相关文章

  1. 后盾网lavarel视频项目---lavarel用户认证实例

    后盾网lavarel视频项目---lavarel用户认证实例 一.总结 一句话总结: 主要是用的Auth认证,所以配置是配置的auth(config/auth.php),控制器中调用也是用的Auth( ...

  2. 后盾网lavarel视频项目---lavarel多表关联一对多操作实例

    后盾网lavarel视频项目---lavarel多表关联一对多操作实例 一.总结 一句话总结: 1.一对多中多那个部分的数据前端通过json弄到服务器 2.所有通过一操作多的时候,都要用上模型中定义的 ...

  3. 后盾网lavarel视频项目---lavarel中的tinker是什么

    后盾网lavarel视频项目---lavarel中的tinker是什么 一.总结 一句话总结: 是用来调试laravel,可以打印变量或对象信息,显示函数代码,对数据库写入和查询数据 laravel中 ...

  4. 后盾网lavarel视频项目---lavarel中间件(使用中间件拦截没登录的用户)

    后盾网lavarel视频项目---lavarel中间件(使用中间件拦截没登录的用户) 一.总结 一句话总结: 1.中间件中验证用户是否登录:if(!Auth::guard('admin')->c ...

  5. Online Coding开发模式 (通过在线配置实现一个表模型的增删改查功能,无需写任何代码)

    JEECG 智能开发平台. 开发模式由代码生成器转变为Online Coding模式                      (通过在线配置实现一个表模型的增删改查功能,无需一行代码,支持用户自定义 ...

  6. 48.Python中ORM模型实现mysql数据库基本的增删改查操作

    首先需要配置settings.py文件中的DATABASES与数据库的连接信息, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.my ...

  7. 如何搭建一个WEB服务器项目(二)—— 对数据库表进行基本的增删改查操作

    使用HibernateTemplate进行增删改查操作 观前提示:本系列文章有关服务器以及后端程序这些概念,我写的全是自己的理解,并不一定正确,希望不要误人子弟.欢迎各位大佬来评论区提出问题或者是指出 ...

  8. 基于renren-fast的快速入门项目实战(实现报表增删改查)

    基于renren-fast的快速入门项目实战(实现报表增删改查) 说明:renren-fast是一个开源的基于springboot的前后端分离手脚架,当前版本是3.0 官方开发文档需付费,对于新手而言 ...

  9. 潭州课堂25班:Ph201805201 django框架 第六课 模型类增删改查,常用 的查询矣查询条件 (课堂笔记)

    在视图函数中写入增删改查的方法 增: 在 urls 中配置路径 : 查: 1: 在后台打印数据 在模型类中添加格式化输出 : QuerySet,反回的是个对象,可以按索引聚会,用 for 循环,, 找 ...

随机推荐

  1. Java中“==”与equals的区别以及equals方法的重写

    一.“==”与equals的区别: (1)==代表比较双方是否相同: 基本数据类型表示值相等. 引用数据类型表示地址相等,即同一个对象. (2)Object中的equals()方法:是否为同一个对象的 ...

  2. 大型分布式爬虫准备 scrapy + request

    那些高手 爬虫好文 而我避免这些问题的方式,控制台清除所有定时 var id = setInterval(function() {}, 0); while (id--) clearInterval(i ...

  3. 使用shell脚本自动打包上传 fir.im

    http://blog.csdn.net/wang631106979/article/details/52299083

  4. 安装Maatwebsite \ EXCEL \ ExcelServiceProvider

    安装时报错 composer You can also run `php --ini` inside terminal to see which files are used by PHP in CL ...

  5. Hibernate的缓存(收集)

    (1)缓存就是把以前从数据库中查询出来和使用过的对象保存在内存中(一个数据结构中),这个数据结构通常是或类似Hashmap,当以后要使用某个对象 时,先查询缓存中是否有这个对象,如果有则使用缓存中的对 ...

  6. touch cyusbConfig.cmake

    touch cyusbConfig.cmake cmake文件丢失,与其解决问题,不如临时建立一个临时文件

  7. 第06课:GDB 常用命令详解(下)

    本课的核心内容: disassemble 命令 set args 和 show args 命令 tbreak 命令 watch 命令 display 命令 6.1 disassemble 命令 当进行 ...

  8. cmd命令行显示中文乱码

    cmd命令行显示中文乱码多数是由于字符编码不匹配导致. 1.查看cmd编码方式 方法一.打开cmd,输入chcp命令回车(显示默认编码:活动代码页:936指GBK) 方法二.打开cmd在标题栏单击鼠标 ...

  9. html背景图不随滚轮滚动,而且按住Ctrl并滚动滚轮时,图片不会变大缩小,就像百度的首页一样

    之前在百度知道我提问过这一个问题,后来解决了.不过好多人来问我时怎么解决的,源码.其实很简单.这里我贴一下代码.有需要的小伙伴不用再加我qq了,直接来这里取吧. 里面的图片是我随便找的. <!D ...

  10. [Atcoder2292] Division into Two

    题目大意 给定n个不同的整数,求将它们分成两个集合X,Y,并且X集合中任意两个数的差>=A,Y集合中任意两个数的差>=B的方案数. 样例输入 5 3 7 1 3 6 9 12 样例输出 5 ...