How to Create a Blog with Laravel 5+ Part 6 (CRUD Categories)
Just like from the previous CRUD part and series this part focuses on CRUD categories and back-end functionality, this does not make any difference from Post and Page CRUD we previously created, so mostly what we do here is a copy and paste from our previous work. It is important though to include Category in our Blog to group our post into a certain category and it also assists readers in finding the right type of content on your site.
Let’s get started.
views/categories
Lets sort blade files first used in the back-end view.
|-- create.blade.php
|-- edit.blade.php
|-- index.blade.php
|-- show.blade.php
CategoriesController.php
We already created this Controller back in the previous part, lets fill it with some code needed, this is where CRUD category happens.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Category;
use Session;
class CategoriesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// Fetch records in pagination so only 10 categories per page
// To get all records you may use get() method
$categories = Category::paginate( 10 );
return view('categories.index', ['categories' =--> $categories]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
return view('categories.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'category_name' => 'required|max:200',
'category_slug' => 'required|alpha_dash|max:200|unique:categories,category_slug',
]);
$category = new Category;
$category->category_name = $request->category_name;
$category->category_slug = $request->category_slug;
$category->save();
Session::flash('success', 'Category added.');
return redirect()->route('categories.show', $category->id);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$category = Category::findOrFail( $id );
return view('categories.show', ['category' => $category]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$category = Category::findOrFail( $id );
return view('categories.edit', ['category' => $category]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'category_name' => 'required|max:200',
'category_slug' => 'required|alpha_dash|max:200|unique:categories,category_slug,'.$id,
]);
// Instead of creating new Category Class initialization
// We fetch the category to edit instead
$category = Category::findOrFail( $id );
$category->category_name = $request->input('category_name');
$category->category_slug = $request->input('category_slug');
$category->save();
Session::flash('success', 'Category updated.');
return redirect()->route('categories.show', $id);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$category = Category::findOrFail( $id );
$category->delete();
Session::flash('success', 'Category deleted.');
return redirect()->route('categories.index');
}
}
Now that our Controller is ready, let’s work on views.
index.blade.php
This file is used to display lists of added categories.
@extends('main')
@section('title', '| Categories')
@section('content')
<div class="container">
{{-- Check if current user is logged-in or a guest --}}
@if (Auth::guest())
<p class="mt-5">Cheatn?, please <a href="/login/">login</a> to continue.</p>
@else
<div class="blog-header">
<h1 class="blog-title">Categories <a class="btn btn-sm btn-primary" href="{{ route('categories.create') }}">Add New</a></h1>
</div>
<div class="row">
<div class="col-md-12">
<table class="table">
<tr>
<th>Title</th>
<th>Date</th>
<th> </th>
</tr>
<tr>
{{-- Blade if and else --}}
@if( $categories )
{{-- Blade foreach --}}
@foreach( $categories as $category )
<tr>
<td>
<strong>
<a href="{{ route('categories.edit', $category->id) }}">
{{ $category->category_name }}
</a>
</strong>
</td>
<td>Published {{ date( 'j/m/Y', strtotime( $category->created_at ) ) }}</td>
<td>
<form class="d-inline" action="{{ route('categories.destroy', $category->id) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<input type="submit" value="Delete" class="btn btn-sm btn-danger" />
</form>
<a class="btn btn-sm btn-info" href="{{ route('categories.edit', $category->id) }}">Edit</a>
</td>
</tr>
@endforeach
@endif
</tr>
</table>
{{ $categories->links() }}
</div>
</div>
@endif
</div>
@endsection
create.blade.php
This file is used to create new Category.
@extends('main')
@section('title', '| Add New Category')
@section('content')
<div class="container">
{{-- Check if current user is logged-in or a guest --}}
@if (Auth::guest())
<p class="mt-5">Please <a href="/login/">login</a> to add a new post.</p>
@else
<div class="blog-header">
<h1 class="blog-title">Add New Category</h1>
</div>
<div class="row">
<div class="push-md-2 col-md-8">
<form action="{{ route('categories.store') }}" method="POST">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('category_name') ? ' has-error' : '' }}">
<label for="category_name">Title</label> <br/>
<input type="text" name="category_name" id="category_name" value="{{ old('category_name') }}" />
@if ($errors->has('category_name'))
<span class="help-block">
<strong>{{ $errors->first('category_name') }}</strong>
</span>
@endif
</div>
<div class="form-group{{ $errors->has('category_slug') ? ' has-error' : '' }}">
<label for="category_slug">Slug</label> <br/>
<input type="text" name="category_slug" id="category_slug" value="{{ old('category_slug') }}" />
@if ($errors->has('category_slug'))
<span class="help-block">
<strong>{{ $errors->first('category_slug') }}</strong>
</span>
@endif
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Publish" />
<a class="btn btn-primary" href="{{ route('categories.index') }}">Cancel</a>
</div>
</form>
</div>
</div>
@endif
</div>
@endsection
edit.blade.php
This file is used to edit certain or selected category.
@extends('main')
@section('title', '| Add New Category')
@section('content')
<div class="container">
{{-- Check if current user is logged-in or a guest --}}
@if (Auth::guest())
<p class="mt-5">Please <a href="/login/">login</a> to add a new post.</p>
@else
<div class="blog-header">
<h1 class="blog-title">Add New Category</h1>
</div>
<div class="row">
<div class="push-md-2 col-md-8">
{{--
Check route:list for `posts.update` for more info
URL is posts/{post}, `{post}` meaning that we have to supply ID
--}}
<form action="{{ route('categories.update', $category->id) }}" method="POST">
{{ csrf_field() }}
{{--
HTML forms do not support PUT, PATCH or DELETE actions.
So, when defining PUT, PATCH or DELETE routes that are called from an HTML form,
you will need to add a hidden _method field to the form.
--}}
{{ method_field('PUT') }}
<div class="form-group{{ $errors->has('category_name') ? ' has-error' : '' }}">
<label for="category_name">Title</label> <br/>
<input type="text" name="category_name" id="category_name" value="{{ $category->category_name }}" />
@if ($errors->has('category_name'))
<span class="help-block">
<strong>{{ $errors->first('category_name') }}</strong>
</span>
@endif
</div>
<div class="form-group{{ $errors->has('category_slug') ? ' has-error' : '' }}">
<label for="category_slug">Slug</label> <br/>
<input type="text" name="category_slug" id="category_slug" value="{{ $category->category_slug }}" />
@if ($errors->has('category_slug'))
<span class="help-block">
<strong>{{ $errors->first('category_slug') }}</strong>
</span>
@endif
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Update" />
<a class="btn btn-primary" href="{{ route('categories.index') }}">Cancel</a>
</div>
</form>
</div>
</div>
@endif
</div>
@endsection
show.blade.php
Just like from Post and Page CRUD this file is used to display newly added category.
@extends('main')
@section('title')
{{ $category->category_name }}
@endsection
@section('content')
<div class="container">
{{-- Check if current user is logged-in or a guest --}}
@if (Auth::guest())
<p class="mt-5">Cheatn?, please <a href="/login/">login</a> to continue.</p>
@else
<div class="blog-header">
<h1 class="blog-title">{{ $category->category_name }}</h1>
<p>{{ date('M j, Y', strtotime( $category->created_at )) }} <a href="{{ route('categories.edit', $category->id) }}">{Edit}</a></p>
</div>
@endif
</div>
@endsection
That’s pretty much it and we’re done, happy coding ^_^, see ya in the next part.