上一篇说了laravel用crud之index列出产品items,我们现在试着添加产品,用到CRUD的 Create 和 Store 方法,打开/app/Http/Controllers/ItemController.php定义一下create和store方法
1,添加新产品
public function create()
{
return view('items.create');
}
2,保存刚刚添加的产品到数据库
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|unique:items|max:255',
'price' => 'required|numeric',
'img' => 'required|max:255',
'description' => 'required|max:255',
]);//检查输入是否合法
//
$item = New Item; $item->name = $request->name;
$item->price = $request->price;
$item->img = $request->img;
$item->description = $request->description; $item->save(); }
3,写create.blade.php模板,文件在/resources/views/items/create.blade.php,添加如下代码
@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="panel panel-default">
<div class="panel-heading">Create New Item</div>
<div class="panel-body">
<form method="POST" action="/items" aria-label="Register">
@csrf
<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="" 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="" 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">
</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">
</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
打开http://lawoole.z5w.net/items/create添加产品,然后去数据库看看是不是增加了一个新产品