index, create, update, deleteの順番に作ります。
最初にindexで表示項目のデータをDBに入れておく。
$ php artisan make:controller –resource AdminCategoriesController
Route::group(['middleware'=>'admin'], function(){ Route::resource('admin/users', 'AdminUsersController'); Route::resource('admin/posts', 'AdminPostsController'); Route::resource('admin/categories', 'AdminCategoriesController'); });
AdminCategoriesController.php
public function index() { $categories = Category::all(); return view('admin.categories.index', compact('categories')); }
layouts/admin.blade.php
<li> <a href="{{route('admin.categories.index')}}">All Categories</a> </li> <li> <a href="{{route('admin.categories.create')}}">Create Category</a> </li>
categories/index.blade.php
<h1>Categories</h1> <div class="col-sm-6"> {!! Form::open(['method'=>'POST', 'action'=>'AdminCategoriesController@store']) !!} {{ csrf_field()}} <div class="form-group"> {!! Form::label('name', 'Name') !!} {!! Form::text('name', null, ['class'=>'form-control']) !!} </div> <div class="form-group"> {!! Form::submit('Create Category', ['class'=>'btn btn-primary']) !!} </div> {!! Form::close() !!} </div> <div class="col-sm-6"> @if($categories) <table class="table table-striped"> <thead> <tr> <th>Id</th> <th>Category</th> <th>Created date</th> </tr> </thead> <tbody> @foreach($categories as $category) <tr> <td>{{$category->id}}</td> <td>{{$category->name}}</td> <td>{{$category->created_at ? $category->created_at->diffForhumans() : 'no date'}}</td> </tr> @endforeach </tbody> </table> @endif </div>
AdminCategoriesController.php
public function store(Request $request) { // Category::create($request->all()); return redirect('/admin/categories'); } public function edit($id) { // $category = Category::findOrFail($id); return view('admin.categories.edit', compact('category')); }
view: index.blade.php
<tr> <td>{{$category->id}}</td> <td><a href="{{route('admin.categories.edit', $category->id)}}">{{$category->name}}</a></td> <td>{{$category->created_at ? $category->created_at->diffForhumans() : 'no date'}}</td> </tr>
AdminCategoriesController.php
public function destroy($id) { Category::findOrFail($id)->delete(); return view('/admin/categories'); }
Keep going!
気分転換に馬喰町のロボットコーヒーでも行くかな☕