laravel用crud之index列出产品items

  前面我们说了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')
List of Items
@foreach($items as $item) @endforeach
# Name Price Img description Created At Update At Actions
{{$item->id}} {{$item->name}} {{$item->price}} {{$item->img}} {{$item->description}} {{$item->created_at}} {{$item->updated_at}} view delete
Create New Item
@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')
List of Items
@foreach($items as $item) @endforeach
# Name Price Img description Created At Update At Actions
{{$item->id}} {{$item->name}} {{$item->price}} {{$item->img}} {{$item->description}} {{$item->created_at}} {{$item->updated_at}} view delete
{{$items->links()}}
//分页链接 Create New Item
@endsection

  

  2,打开试一下http://lawoole.z5w.net/items?page=2

你可能感兴趣的:(php)