You are currently viewing Part IX: How to Delete a Post and Final Admin Dashboard Touch in Laravel 5.7 and Php 7.2

Part IX: How to Delete a Post and Final Admin Dashboard Touch in Laravel 5.7 and Php 7.2

Hello and welcome to this tutorial series, my name is Henry and I will be taking you through the various aspect of creating a simple blog system using Laravel web framework. In Part VIII, we learnt how to edit and update our post. In this Lesson, we are going to learn how to delete a post.

To delete a record in database using Laravel, we need to call delete method on a model instance. Open HomeController and make sure it has the following code:

<?php

namespace App\Http\Controllers;

use App\Blog;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }

    public function getRegisteredUsers()
    {
        $users = User::orderBy('id', 'DESC')->get();
        return view('users', ['users' => $users]);
    }


    /**
     * A function to show a list of all blog posts
     */

    public function PostList()
    {
        $posts = Blog::with('writer')->get();
//        dd($posts);
        return view('post_list', ['posts' => $posts]);
    }


    /**
     * A function to show a form to create post
     */

    public function createPost()
    {
        return view('post_create');
    }


    /**
     * A function to store our post
     */

    public function storePost(Request $request)
    {
        $request->validate([
                'title' => 'required',
                'body' => 'required',
                'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            ]
        );

        $image = $request->file('image');
        $input['imagename'] = time().'.'.$image->getClientOriginalExtension();
        $destinationPath = public_path('/images');
        $image->move($destinationPath, $input['imagename']);

        $article = new Blog();
        $article->title = $request->get('title');
        $article->body = $request->get('body');
        $article->author = Auth::id();
        $article->image = $input['imagename'];
        $article->save();
        return redirect()->route('all_posts')->with('status', 'New article has been successfully created!');
    }

    public function editPost($post_id)
    {
        $post = Blog::find($post_id);
        return view('edit_form', ['post' => $post]);
    }

    public function updatePost(Request $request, $post_id)
    {
        $post = Blog::find($post_id);
        $post->title = $request->get('title');
        $post->body = $request->get('body');

        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $input['imagename'] = time().'.'.$image->getClientOriginalExtension();
            $destinationPath = public_path('/images');
            $image->move($destinationPath, $input['imagename']);
            $post->image = $input['imagename'];
        }
        $post->save();
        return redirect()->route('all_posts')->with('status', 'Post has been successfully updated!');

    }


    public function deletePost($post_id)
    {
        $post = Blog::find($post_id);
        $post->delete();
        return redirect()->route('all_posts')->with('status', 'Post has been successfully delete!');
    }

}

Let’s understand the code:

  • Line 113 to 118 – we have created a function called deletePost which accept one parameter, in our case is post_id.
  • Line 115 – we find the record we intend to delete.
  • Line 116 – we called delete method on our model instance. We delete the record from our database.
  • Line 117 – we redirect a user with a success message that post has been deleted.

Update Web.php File

The next step is to edit the web.php file, we need to add a route that goes to our deletePost method. Open the web.php file and make sure it has the following code:

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::get('/registered/users', 'HomeController@getRegisteredUsers')->name('registered_users');
Route::get('/all/posts', 'HomeController@PostList')->name('all_posts');
Route::get('/create/post', 'HomeController@createPost')->name('create_post');
Route::post('/store/post', 'HomeController@storePost')->name('store_new_post');
Route::get('/edit/post/{post_id}', 'HomeController@editPost')->name('edit_post_form');
Route::post('/update/post/{post_id}', 'HomeController@updatePost')->name('update_post');
Route::post('/delete/post/{post_id}', 'HomeController@deletePost')->name('delete_post');

Line 27 – we create a route named delete_post, we have also added place holder called post_id and the last thing is that our route uses post method. The main reason for using post is for security reason so that user cannot manipulate our deleting url.

The last thing we need to do is to update our post_list.blade.php file and make sure it has the following code.

@extends('layouts.app')

@section('content')
    <div class="container-fluid">
        <div class="row">
            @include('partials.sidenavbar')

            <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">All Posts

                    </h1>
                    <a href="{{ route('create_post') }}" class="btn btn-primary float-right">Add Post</a>
                </div>

                @if (session('status'))
                    <div class="alert alert-success">
                        {{ session('status') }}
                    </div>
                @endif

                <div class="row">
                    @foreach($posts as $post)
                        <div class="col-md-4">
                            <div class="card" style="width: 18rem;">
                                @if($post->image)
                                    <img class="card-img-top" src="{{ asset('images/'.$post->image) }}" alt="Blog Post Image">
                                @endif
                                <div class="card-body">
                                    <h5 class="card-title">{{ $post->title }} by <small><i>{{ $post->writer->name }}</i></small></h5>
                                    <p class="card-text">
                                        {{ $post->body }}
                                    </p>
                                    <a href="{{ route('edit_post_form', ['post_id' => $post->id]) }}" class="card-link btn btn-primary">Edit</a>
                                    <form action="{{ route('delete_post', ['post_id' => $post->id]) }}" method="post"><br>
                                        {{ csrf_field() }}
                                        <button type="submit" class="btn btn-danger" >delete</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>


            </main>
        </div>
    </div>
@endsection

Let’s understand the code:

  • Line 35 to 38 – we have created a form which uses our delete URL in the form action
  • Line 36 – we use csrf_field to generate a unique token to prevent cross-site forgery.
  • Line 37 – we create a submit button for users to click.

Make sure your development server is running and navigate to the post list page:

Click on the delete button and see what happens. Here is the output after clicking the delete button.

Now, we know how to delete a record in the database. You can improve on the look and feel of how admin dashboard looks like. Learn more about bootstrap framework.

Final Touches In our Admin Dashboard

When we login to our dashboard we get the following screen:

I would like to improve on this empty screen, open HomeController and make sure it has the following code.

<?php

namespace App\Http\Controllers;

use App\Blog;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $number_of_posts = Blog::count();
        $number_of_authors = User::count();
        $new_posts = Blog::orderBy('id', 'DESC')->take(5)->get();
        $new_authors = User::orderBy('id', 'DESC')->take(5)->get();

        $data = [
            'post_count' => $number_of_posts,
            'author_count' => $number_of_authors,
            'new_posts' => $new_posts,
            'new_authors' => $new_authors,
        ];

        return view('home', $data);
    }

    public function getRegisteredUsers()
    {
        $users = User::orderBy('id', 'DESC')->get();
        return view('users', ['users' => $users]);
    }


    /**
     * A function to show a list of all blog posts
     */

    public function PostList()
    {
        $posts = Blog::with('writer')->get();
//        dd($posts);
        return view('post_list', ['posts' => $posts]);
    }


    /**
     * A function to show a form to create post
     */

    public function createPost()
    {
        return view('post_create');
    }


    /**
     * A function to store our post
     */

    public function storePost(Request $request)
    {
        $request->validate([
                'title' => 'required',
                'body' => 'required',
                'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            ]
        );

        $image = $request->file('image');
        $input['imagename'] = time().'.'.$image->getClientOriginalExtension();
        $destinationPath = public_path('/images');
        $image->move($destinationPath, $input['imagename']);

        $article = new Blog();
        $article->title = $request->get('title');
        $article->body = $request->get('body');
        $article->author = Auth::id();
        $article->image = $input['imagename'];
        $article->save();
        return redirect()->route('all_posts')->with('status', 'New article has been successfully created!');
    }

    public function editPost($post_id)
    {
        $post = Blog::find($post_id);
        return view('edit_form', ['post' => $post]);
    }

    public function updatePost(Request $request, $post_id)
    {
        $post = Blog::find($post_id);
        $post->title = $request->get('title');
        $post->body = $request->get('body');

        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $input['imagename'] = time().'.'.$image->getClientOriginalExtension();
            $destinationPath = public_path('/images');
            $image->move($destinationPath, $input['imagename']);
            $post->image = $input['imagename'];
        }
        $post->save();
        return redirect()->route('all_posts')->with('status', 'Post has been successfully updated!');

    }


    public function deletePost($post_id)
    {
        $post = Blog::find($post_id);
        $post->delete();
        return redirect()->route('all_posts')->with('status', 'Post has been successfully delete!');
    }

}

Let’s understand the code:

  • We have edited our index method.
  • Line 29 – we are counting how many posts we have in our databases.
  • Line 30 – we are counting the number of authors in our database.
  • Line 31 – we are taking 5 latest post from our database.
  • Line 32 – we are taking 5 newly added authors from our databases.
  • Line 34 to 39 – we create an array and pass the result of each query.
  • Line 41 – we pass our data to our view.

Let’s edit home.blade.php file and make sure it has the following code.

@extends('layouts.app')

@section('content')
    <div class="container-fluid">
        <div class="row">
            @include('partials.sidenavbar')

            <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Dashboard</h1>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="card text-center">
                            <div class="card-block">
                                <h4 class="card-title">Number of posts</h4>
                            </div>
                            <div class="row px-2 no-gutters">
                                <div class="col-6">
                                    <h3 class="card card-block border-top-0 border-left-0 border-bottom-0">
                                        <i class="fa fa-file fa-3x" style="color: #1d68a7"></i>
                                    </h3>
                                </div>
                                <div class="col-6">
                                    <br>
                                    <h3 class="card card-block border-0">{{ $post_count }}</h3>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="card text-center">
                            <div class="card-block">
                                <h4 class="card-title">Number of authors</h4>
                            </div>
                            <div class="row px-2 no-gutters">
                                <div class="col-6">
                                    <h3 class="card card-block border-top-0 border-left-0 border-bottom-0">
                                        <i class="fa fa-users fa-3x" style="color: #1d68a7"></i>
                                    </h3>
                                </div>
                                <div class="col-6">
                                    <br>
                                    <h3 class="card card-block border-0">{{ $author_count }}</h3>
                                </div>
                            </div>
                        </div>
                    </div>


                </div>

                <br>
                <div class="row">
                    <div class="col-md">
                        <div class="card bg-success" >
                            <div class="card-header text-white">
                                Latest Post
                            </div>
                            <ul class="list-group list-group-flush">
                                @foreach($new_posts as $post)
                                    <li class="list-group-item">{{ $post->title }}</li>
                                @endforeach
                            </ul>
                        </div>

                    </div>

                    <div class="col-md">
                        <div class="card bg-success" >
                            <div class="card-header text-white">
                                New Authors
                            </div>
                            <ul class="list-group list-group-flush">
                                @foreach($new_authors as $author)
                                    <li class="list-group-item">{{ $author->name }}</li>
                                @endforeach
                            </ul>
                        </div>

                    </div>

                </div>

            </main>
        </div>
    </div>
@endsection

Let’s understand the code:

  • Line 12 to 52 – we have created a bootstrap row.
  • Line 13 to 30 – we have created a bootstrap card.
  • Line 16 – we give the title of our card.
  • Line 21 – we use the font awesome icon.
  • Line 26 – we display the number of posts in our database.
  • Line 32 to 49 – we create another bootstrap card.
  • Line 35 – we display the title of the card.
  • Line 40 – we use font awesome icon.
  • Line 45 – we display the number of authors in our database.
  • Line 55 to 84 – we create another bootstrap row.
  • Line 57 to 66 – we create a bootstrap card.
  • Line 62 to 64 – we loop through the current posts and display their title on line 63.
  • Line 76 to 78 – we loop through the current authors and we display author’s name on line 77. Make sure your development server is running and login to your application. You should see the following screen:

With that we conclude our blog admin portal, there are so many things you can do to improve this admin dashboard. In our next tutorial, we will learn how to display our posts to the public page.

NB: Remember to include font awesome cdn link in your app.blade.php file. Learn more about fonts for the designer.

Task

Try to implement the ability such that a site visitors can view blog posts without being logged in.

In the next lesson, we will be implementing the ability for site visitor to view our blog posts, step by step together with you and this lesson has given us a great starting point. See you in Lesson X

You can grab the code used in this tutorial at blog application in Laravel 5.7

Facebook Comments