上一篇讲了Laravel展示产品-CRUD之show,现在我们说一下Laravel编辑产品,涉及到编辑和更新,
1,定义controller,update和create有点相似,我们复制一份过来修改。new item改为item::find
public function edit($id) { // $item = Item::find($id); return view(‘items.edit‘)->with(‘item‘, $item); } public function update(Request $request, $id) { $validatedData = $request->validate([ ‘name‘ => ‘required|max:255‘, ‘price‘ => ‘required|numeric‘, ‘img‘ => ‘required|max:255‘, ‘description‘ => ‘required|max:255‘, ]);//检查输入是否合法 $item = Item::find($id); $item->name = $request->name; $item->price = $request->price; $item->img = $request->img; $item->description = $request->description; $item->save(); }
2,编辑edit.blade.php,文件在/resources/views/items/edit.blade.php,添加如下代码,注意method是PUT
@extends(‘layouts.app‘) @if ($errors->any()) <div class="alert alert-danger"> <strong>Errors:</strong> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif @section(‘content‘) <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="card card-default"> <div class="card-header">Edit Item</div> <div class="card-body"> <form method="POST" action="{{route(‘items.update‘, $item->id)}}" aria-label="Register"> @csrf <input type="hidden" name="_method" value="PUT"> <div class="form-group row"> <label for="name" class="col-md-4 col-form-label text-md-right">Name</label> <div class="col-md-6"> <input id="name" type="text" name="name" value="{{ $item->name }}" required="required" autofocus="autofocus" class="form-control"> </div> </div> <div class="form-group row"> <label for="email" class="col-md-4 col-form-label text-md-right">Price</label> <div class="col-md-6"> <input id="email" type="text" name="price" value="{{ $item->price }}" required="required" class="form-control"> </div> </div> <div class="form-group row"> <label for="password" class="col-md-4 col-form-label text-md-right">Img</label> <div class="col-md-6"> <input id="password" type="text" name="img" class="form-control" value="{{ $item->img }}"> </div> </div> <div class="form-group row"> <label for="password-confirm" class="col-md-4 col-form-label text-md-right">Description</label> <div class="col-md-6"> <input id="password-confirm" type="text" name="description" required="required" class="form-control" value="{{ $item->description }}"> </div> </div> <div class="form-group row mb-0"> <div class="col-md-6 offset-md-4"> <button type="submit" class="btn btn-primary">Save</button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
原文地址:https://www.cnblogs.com/ytkah/p/9291157.html
时间: 2024-10-21 06:35:09