laravel笔记5 无线分类2
错误提示
Undefined variable: cates (View: E:\phpStudy_64\phpstudy_pro\WWW\yfkt.com\resources\views\admin\category\edit.blade.php)
解决:1、检查路由里面有没有传递具体分类的参数id
2、这里在blade里面看到获取数据的时候有$cates 所以需要到控制器里在需要编辑数据的时候先获取到数据,然后with到blade里面
<label for="pid">上级分类</label>
<select class="form-control" name = 'pid' id="pid">
<option value="0">顶级分类</option>
@foreach ($cates as $item)
<option value="{{$item->id}}" {{($item->id==$cate->pid)?'selected':''}}>
{{($item->level==0)?'':'|'}}{{str_repeat('-----',$item->level)}}{{$item->name}}
</option>
@endforeach
</select>
解决:
//添加分类
public function create(Request $request){
if($request->isMethod('post')){
// dd($request->post());
$category = new Category();
$category->name = $request->name;
$category->sort = $request->sort;
$category->pid = $request->pid;
$result = $category->save();
//上述结果如果添加成功返回的是布尔值
checkreturn($result,'添加');
return redirect(route('admin.category.list'));
}
//在这里$cates就是从模型里获取的数据
$cates = Category::getcates();
return view('admin.category.create')->with('cates',$cates);
}
public function edit(Category $cate){
//编辑页面添加已有数据,然后才能编辑
$cates = Category::getcates();
//用with继续渲染到blade里面
return view('admin.category.edit')->with('cate',$cate)->with('cates',$cates);
}
*********************************************************************************
如果不使用resource路由的话,编辑的时候action直接等于?即可,因为之前已经获取到了要修改的id
<form class="forms-sample" action=? method="POST">
@csrf
<div class="form-group">
<label for="pid">上级分类</label>
<select class="form-control" name = 'pid' id="pid">
<option value="0">顶级分类</option>
@foreach ($cates as $item)
<option value="{{$item->id}}" {{($item->id==$cate->pid)?'selected':''}}>
{{($item->level==0)?'':'|'}}{{str_repeat('-----',$item->level)}}{{$item->name}}
</option>
@endforeach
</select>
</div>
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
产品编辑修改
public function edit(Request $request,Category $category){
if($request->isMethod('post')){
//在编辑数据然后写入数据库的时候,不用在new实例化一个模型了,否则编辑的数据不会被覆盖,而是新增一条数据
$category = new Category();
$category->name = $request->name;
$category->sort = $request->sort;
$category->pid = $request->pid;
$result = $category->save();
//上述结果如果添加成功返回的是布尔值
checkreturn($result,'添加');
return redirect(route('admin.category.list'));
}
$cates = Category::getcates();
return view('admin.category.edit')->with('cate',$category)->with('cates',$cates);
}
产品删除
public function destroy(Category $cate){
$result = $cate->delete();
//下面这行代码是调用的自定义的公共函数 可查看之前的笔记
checkreturn($result,'删除');
return redirect(route('admin.category.list'));
}
}