前面我们说了laravel用crud修改产品items-新建resource controller和routing,现在我们要把产品items罗列出来,需要修改路由和模板,一起随ytakh来看看把
1,修改controller,/app/Http/Controllers/ItemController.php
use App\Item;
//还有下面的index定义
public function index()
{
//
$items = Item::all();
return view('items.index')->with('items',$items);
}
2,修改index.blade.php模板
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">List of Items</div>
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Price</th>
<th>Img</th>
<th>description</th>
<th>Created At</th>
<th>Update At</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach($items as $item)
<tr>
<td>{{$item->id}}</td>
<td>{{$item->name}}</td>
<td>{{$item->price}}</td>
<td>{{$item->img}}</td>
<td>{{$item->description}}</td>
<td>{{$item->created_at}}</td>
<td>{{$item->updated_at}}</td>
<td>
<a class="btn btn-primary" href="{{route('items.show', '$item->id')}}">view</a>
<a class="btn btn-danger" href="{{route('items.destroy', '$item->id')}}">delete</a>
</td>
</tr>
@endforeach
</tbody>
</table>
<a class="btn btn-primary" href="{{route('items.create')}}">Create New Item</a>
</div>
</div>
</div>
</div>
</div>
@endsection
上面是用于产品比较少的情况,如果产品多了,我们就要进行分页才好点,怎么做分页呢?用到paginate
1,修改controller,/app/Http/Controllers/ItemController.php
use App\Item;
use DB;
//还有下面的function定义
public function index()
{
//
$items = DB::table('items')->paginate(10);//可以调整数字大小,表示一页显示多少各产品
return view('items.index')->with('items',$items);
}
如果要降序排列,即最新上传的产品放在前面,用 ->latest()
$items = DB::table('items')->latest()->paginate(1);
修改index.blade.php模板
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">List of Items</div>
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Price</th>
<th>Img</th>
<th>description</th>
<th>Created At</th>
<th>Update At</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach($items as $item)
<tr>
<td>{{$item->id}}</td>
<td>{{$item->name}}</td>
<td>{{$item->price}}</td>
<td>{{$item->img}}</td>
<td>{{$item->description}}</td>
<td>{{$item->created_at}}</td>
<td>{{$item->updated_at}}</td>
<td>
<a class="btn btn-primary" href="{{route('items.show', '$item->id')}}">view</a>
<a class="btn btn-danger" href="{{route('items.destroy', '$item->id')}}">delete</a>
</td>
</tr>
@endforeach
</tbody>
</table>
<div class="text-center">{{$items->links()}}</div>//分页链接
<a class="btn btn-primary" href="{{route('items.create')}}">Create New Item</a>
</div>
</div>
</div>
</div>
</div>
@endsection
2,打开试一下http://lawoole.z5w.net/items?page=2