You are currently viewing Part VI: How to store and Retrieve a Blog Post in Laravel 5.7 and Php 7.2

Part VI: How to store and Retrieve a Blog Post 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 V of this tutorial series, we created a form to create a post. In this lesson, we are going to learn how to store our post in the database.

So, to get started, we are going to edit our HomeController.php, make sure that HomeController 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()
    {
        return view('post_list');
    }


    /**
     * 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',
            ]
        );

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

}

Let’s understand the code:

  • Line 5 – we have imported our Blog model which we will use to create a new model instance.
  • Line 8 – we have imported Auth façade which we will use to access the authenticated user in our application.
  • Line 65 to 69 – we are trying to validate our blog post using validate method provided by Illuminate/Http/Request
  • Line 66 – we are saying title is required.
  • Line 67 – we are saying body is required.
  • Line 63 to 77 – we have created a function called storePost.
  • Line 71 – we are creating a new blog model instance.
  • Line 72 – we are getting the attribute title from Laravel request and mapping that to the database field called title.
  • Line 73 – we are getting the attribute body from Laravel request and mapping that to the database field called body.
  • Line 74 – we are getting id of authenticated user from Auth façade and mapping that to the database field called author.
  • Line 75 – we are calling Laravel save method on our model instance which will create a new record in our database.
  • Line 76 – we are redirecting to a url called all_posts with a success message which will be displayed.

Learn more about Laravel validation and Laravel eloquent.

The next step is to edit the post_list.blade.php file to make sure we can display our success message when a new post is created. Make sure that post_list.blade.php 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

                


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

Line 16 to 20 – we are creating an in if control statement where we are checking if our session has status. Line 18, if our session has status we display the message.

The next step is to create a URL that goes to the storePost method in our HomeController, open 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');

Line 24 – we have created a route with name store_new_post which goes to our storePost method in HomeController. Before we can test our form, we need to hook our form to post data to the newly created url. Open post_create.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">Create A Post</h1>
                </div>


                    <form action="{{ route('store_new_post') }}" method="post">
                        {{ csrf_field() }}
                        <div class="form-group">
                            <label for="title">Title</label>
                            <input type="text" class="form-control"  aria-describedby="emailHelp" placeholder="Enter blog title" name="title" required>
                        </div>
                        <div class="form-group">
                            <label for="body">Blog Content</label>
                            <textarea class="form-control" rows="5" name="body" required></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary">Create Post</button>
                    </form>

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

Line 14 – we have added our store_new_post route to the action of this form. Line 15, we have added csrf_field() to prevent cross-site forgery. Make sure your development server is running. Log in to your dashboard and click on Posts on the left side navbar. Click on Add post button and you should see the following screen:

Fill in the title, blog content and hit Create Post. You should see the following screen

Great work, we are now able to store our articles. If I check my database, here is a list of post I have created:

From my database, you can see I have created a couple of posts. You can also see on the author field that we have number two. Remember this is a foreign key tied to our user model.

Retrieving All Posts

To retrieve all posts, we need to do a couple of things, open Blog.php model file and make sure it has the following code:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Blog extends Model
{
    /**
     * Get the author that wrote the posts.
     */
    public function writer()
    {
       return $this->belongsTo('App\User', 'author', 'id');
    }
}

Line 12 to 15, we have created a method called writer. Line 14, we are accessing the Eloquent relationship where a post blog belongs to a user. This method is called Eager loading and Laravel do a great job with eager loading since the relationship data is Lazy loaded. The next step is to edit HomeController and update a method called PostList. Make sure that HomeController 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();
        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',
            ]
        );

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

}

Line 45 – we are getting all posts in our database using our blog model. Line 46, we are passing our posts as an array. The next step is to edit post_list.blade.php 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;">
                                {{--<img class="card-img-top" src="..." alt="Blog Post Image">--}}
                                <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="#" class="card-link btn btn-primary">Edit</a>
                                    <a href="#" class="card-link btn btn-danger" >delete</a>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>


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

Let’s understand the code:

  • Line 22 to 38 – we have created a bootstrap row.
  • Line 23 to 37 – we have created a foreach loop which will loop through our posts data that we are passing to this blade.
  • Line 25 to 35 – we are using bootstrap 4 cards.
  • Line 28 – we display the title of the post. We also display the author of the post using the method we wrote on blog model.
  • Line 30 – we display the body of our blog post.

Make sure your development server and navigate to http://127.0.0.1:8000/all/posts you should see the following screens:

Phew! That was a lot of work.

Goal Achieved in this lesson

  • We have learnt how to save new post.
  • We have learnt about validation.
  • We have learnt how to create methods in Laravel model.
  • We have learnt how to fetch posts and display them in our dashboard

Task

Try to create a method to edit and update our posts.

In the next lesson, we will continue building our blog admin portal, step by step together with you and this lesson has given us a great starting point. See you in Lesson VII

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

Facebook Comments