Fetch data and display in views using Laravel

Hi guys! Today I brought a new article based on Laravel. This is mainly written about Laravel Eloquent. What is it? It's an object relational mapper. It makes querying and working with the database very easy. We can use it to handle database records. Since we have much work, without long descriptions let's move to the work.

First you need to create a project using Laravel.
composer create-project --prefer-dist laravel/laravel TestApp

Then go into the project by cd command and run the project using artisan CLI command.
php artisan serve

Open the web browser and type -  http://localhost:8000

Now open your project in a text editor. In my case I use VS code since it has an integrated terminal. You can still use your cmd to run Laravel commands.

First I create a database called laravel_test. Then I need to configure it in my project. This is the configuration. If you don't have an idea to do this, refer this article.

DB configurations - .env file

DB configurations - config/database.php file

Then change the name of the default view; welcome to index. Another several views are needed. Create the with folders according to this structure.


<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/4.0.0/lumen/bootstrap.min.css">
<link href="{{ asset('css/style.css') }}" rel="stylesheet">
<link href="{{ asset('css/style.css') }}" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
<script rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto|Oswald|Michroma" rel="stylesheet" type="text/css">


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="{{ asset('js/script.js') }}"></script>
<script defer src="https://use.fontawesome.com/releases/v5.0.7/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>


<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="#">Laravel Blog</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor02" aria-controls="navbarColor02" aria-expanded="false" aria-label="Toggle navigation" style="">
<span class="navbar-toggler-icon"></span>

<div class="collapse navbar-collapse" id="navbarColor02">
<ul class="navbar-nav ml-auto">
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search">
<button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
<li class="nav-item">
<a class="nav-link" href="#">Blog</a>






For now, posts folder is not needed. Later we can create it.
Now we have to create a controller to load these views.
php artisan make:controller PagesController

Implement it's index function to load the index.blade.php file.



namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PagesController extends Controller
public function index()
return view('index')->withTitle('Laravel Home');

Route should be created to view this file. Open routes/web.php file and enter this code after deleting it's existing routes.
Route::get('/', 'PagesController@index');

Now we need to create a Model to handle DB operations. In my case it's name is Post. Because I'm going to retrieve posts from the database. As a best practice, create the Models with a Singular name. Then migration file will be created automatically with a database table with a plural name. Here, DB table will be posts since my model is Post.
php artisan make:model Post -m

Enter these lines of codes to the Post model.


namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
// table name
protected $table = 'posts';
// primary key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;


Open the migration file created automatically with the model. Most probably the 3rd file in the database/migrations folder. Check whether it has some codes regarding posts table. We have to change the structure of the posts table. Change the up function like this.

public function up()
Schema::create('posts', function (Blueprint $table) {

Important Before migrate...

Before the migration, in latest Laravel versions we have to do another small change to avoid from errors while migrating. Open app/Http/Providers folder and find the AppServiceProvider.php file. We have to enter some code for a successful migration.


namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
* Bootstrap any application services.
* @return void
public function boot()

* Register any application services.
* @return void
public function register()

Now we have to migrate to create the posts table and the others. Tables are shown in the below image.
php artisan migrate

Still the posts table is empty! Now we are going to use Laravel Eloquent.

We can insert data into the DB tables using artisan CLI. This is an amazing feature of Laravel. Hit the below command on cmd to enable the feature to insert data into the DB. 
php artisan tinker

Then load the Post model to the cmd and check the count of the table. Then create a variable to allocate memory and assign the data into the DB table field using that variable. A new variable is needed for every record row.

Now check the posts table in the database. You will see two record rows now!

Ok....This is the most important part of this article. We need a new folder called posts in the resources/views folder. Create a new view in this folder called index.blade.php which is not equal to the previous index blade file. This index view is for viewing all posts.




<div class="container">
<h1 style="margin-top: 30px;" class="text-center">Blog Posts</h1><br>
@foreach($posts as $post)
<div class="card">
<div class="card-header">
<h3><a href="/posts/{{$post->id}}">{{$post->title}}</a></h3>
<div class="card-body">
<div class="card-footer">
<p class="card-text">Published on {{$post->created_at}}</p>
<h3>No posts</h3>

Next thing we have to do is to create a Controller to load this view. But here we need a Resource Controller since we need this controller for CRUD operations of posts. Open cmd and type this command. Resource Controllers are created with a bunch of functions by default. They are; index, create, store, edit, update, show and destroy functions.
php artisan make:controller PostsController --resource

Now edit the index function in this PostsController. Include the Post model at the beginning of the controller.
use App\Post;

Then change the index function like this.

public function index()
$posts = Post::orderBy('id','desc')->paginate(10);
return view('posts.index')->with('posts',$posts)->withTitle('Blog');

Create the Route for this view. Open routes/web.php and implement a new route to view posts.
Route::resource('posts', 'PostsController@index');

Open your web browser and type : http://localhost:8000/posts to see the posts.


Using Laravel, you can easily paginate your database records. CodeIgniter has a lengthy way of implementing pagination. But look at Laravel configuration! It's awesome guys...
Since we are not having more posts, paginate the posts in a way to just to see the pagination links. So I re arrange them for now in this way. After you got the idea, change the pagination count to 10 again.

$posts = Post::orderBy('id','desc')->paginate(1);


You will see the pagination links.


This is the thing that I wanted to show you basically. We can simply retrieve data from database and paginate using Laravel PHP framework! I think you have followed me. If you have questions, please drop a comment here. I will continue and extend this project here on wards. My next article will be based on how to get and display the data according to an ID of a database record. Wait till it comes.. Practice this with your own example..
Good Luck!

No comments :