laravel时间比较、表单验证与数据库相关操作的笔记
2021-03-22 admin laravel mysql 1666
一、常用的时间比较和数据库查询
我们以日志查询为例,需要查询今天、本周、本月、本季度、今年和自定义时间的日志,我们可以使用Carbon:
use Carbon\Carbon;
if(isset($request->cx)){
$today = Carbon::today();
switch ($request->cx)
{
case 1:
$gzrz = Gzrz::whereDate('created_at',$today)->get();//今天
break;
case 2:
$start = $today->startOfWeek()->toDateTimeString();//本周
$end = $today->endOfWeek()->toDateTimeString();
$gzrz = Gzrz::whereBetween('created_at',[$start,$end])->get();
break;
case 3:
$start = $today->firstOfMonth()->toDateTimeString();//本月
$end = $today->endOfMonth()->toDateTimeString();
$gzrz = Gzrz::whereBetween('created_at',[$start,$end])->get();
break;
case 4:
$start = $today->firstOfQuarter()->toDateTimeString();//季度
$end = $today->endOfQuarter()->toDateTimeString();
$gzrz = Gzrz::whereBetween('created_at',[$start,$end])->get();
break;
case 5:
$gzrz = Gzrz::whereYear('created_at',date('Y'))->get();//今年
break;
default:
}
}elseif(isset($request->kssj) && isset($request->jssj)){
$gzrz = Gzrz::whereBetween('created_at',[$request->kssj,$request->jssj])->get();//指定时间
}else{
$gzrz = Gzrz::get();
}
从上面的代码可以看出,laravel查询时间段是非常方便简洁的。
二、常用的表单验证,我们使用use Illuminate\Support\Facades\Validator这个更为方便指定错误提示:
$validator = Validator::make($request->all(),
['bt'=>'required','fl'=>'required','kssj'=>'required','jssj'=>'required','zyjb'=>'required','fzr'=>'required','rwxx'=>'required','cyz'=>'required'],
['bt.required' => '标题不能为空','fl.required' => '分类不能为空','kssj.required' => '开始时间不能为空','jssj.required' => '结束时间不能为空','zyjb.required' => '重要级别不能为空','fzr.required' => '负责人不能为空','rwxx.required' => '任务详细不能为空','cyz.required' => '参与者不能为空'])->validate();
前端可加上以下代码显示:
@foreach (['danger', 'warning', 'success', 'info'] as $msg)
@if(session()->has($msg))
<div class="flash-message">
<p class="alert alert-{{ $msg }}">
{{ session()->get($msg) }}
</p>
</div>
@endif
@endforeach
另外,要上传头像等图片,我们需要注意安全,最好检测图片类型后重新绘制:
if ($request->hasFile('avatar')) {
//接收上传的头像
$file = $request->file('avatar');
$entension = $file->getClientOriginalExtension();//后缀名
$fileName = date('ymdhis').rand(100,999).'.'.$entension;// 随机文件名
$destinationPath = '/uploads/avatar/'; //存放目录
$mimeTye = $file->getMimeType();
if($mimeTye == 'image/jpeg' or $mimeTye == 'image/png' or $mimeTye == 'image/jpg'){
$img = Image::make($file)->resize(300, 300);
$img->save(public_path().$destinationPath.$fileName);
$avatar = url($destinationPath.$fileName);
$data['avatar'] = $avatar;
}else{
return redirect()->back()->with('danger', '上传失败,仅能上传jpg,png图片!');
}
}
上面代码先判断文件是否存在,再判断文件类型,最后将图片压缩重绘制,确保用户上传的安全性。
复杂查询时,需要注意优先级,比如:name=lucy and ( sex=女 or old=11) 这种,需要采用下面的方式:
Renwu::where('bt','like',$bt)->where(function($q1){
$q1->orwhereJsonContains('cyz',(string)Admin::user()->id)
->orwhere('cjz',Admin::user()->id);
})->latest()->get();
这样才能查询到正确的数据。