Laravel 5.8 CRUD Application

Laravel 5.8 CRUD Application

In this tutorial we are going to create a crud application using Laravel 5.8. This tutorial for absolute beginners.

So first install the latest version of Laravel through composer.

After that setup your new laravel project by running the below command on your terminal –

laravel new your-project-name

Database setup

After completing your laravel project setup now open your MySQL server or MariaDB and create a new database called laravel_crud

Now go inside your app folder and open the .env file and change your database info and save it.

set the laravel database information

Creating views

Now open the resources folder then open the views folder and inside the views folder, we’ll create two views – index.blade.php and edit.blade.php.

index.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Laravel CRUD</title>
<!-- UIkit CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.3/css/uikit.min.css" />
<!-- UIkit JS -->
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.3/js/uikit.min.js"></script>

</head>
<body>

<div class="uk-container uk-container-xsmall">
<!-- POST INSERT FORM -->
<form action="" method="POST" novalidate>

<fieldset class="uk-fieldset">

<legend class="uk-legend uk-text-uppercase">Add New Post</legend>

<div class="uk-margin">
<label class="uk-text-bold">Post Title</label>
<input class="uk-input" type="text" placeholder="Post title" name="title" value="{{ old('title') }}">
</div>

<div class="uk-margin">
<label class="uk-text-bold">Post Content</label>
<textarea class="uk-textarea" rows="5" placeholder="Write here..." name="content">{{ old('content') }}</textarea>
</div>

@if ($errors->any())
<div class="uk-alert-danger" uk-alert>
<a class="uk-alert-close" uk-close></a>
@foreach ($errors->all() as $error)
<p>{{ $error }}</p>
@endforeach
</div>
@endif

<div class="uk-margin">
<button class="uk-button uk-button-primary" type="submit">POST</button>
</div>

</fieldset>
@csrf
</form>
<!-- END OF POST INSERT FORM -->


<h2 class="uk-heading-line uk-text-left"><span>All Posts</span></h2>

<!-- SHOW ALL POSTS -->
@forelse($data as $post)
<article class="uk-article">

<h3 class="uk-article-title">{{$post->title}}</h3>

<p class="uk-article-meta"><strong>Posted on</strong> - <i>{{$post->created_at->format('d M, Y')}}</i></p>

<p class="uk-text-justify">{!! $post->content !!}</p>
<div class="uk-grid-small uk-child-width-auto" uk-grid>
<div>
<a class="uk-button uk-button-default" href="/edit/{{$post->id}}">Edit</a>
</div>
<div>
<a class="uk-button uk-button-danger" href="/delete/{{$post->id}}">Delete</a>
</div>
</div>

</article>
<hr class="uk-divider-icon">
@empty
    <p>There are no posts. Please insert some posts.</p>
@endforelse
<!-- END OF SHOW ALL POSTS -->

</div>

</body>
</html>

edit.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Laravel CRUD</title>
<!-- UIkit CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.3/css/uikit.min.css" />
<!-- UIkit JS -->
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.3/js/uikit.min.js"></script>

</head>
<body>

<div class="uk-container uk-container-xsmall">

<div class="uk-margin uk-margin-top">
<a href="/" class="uk-button uk-button-secondary">Go Home</a>
</div>
<!-- EDIT FORM -->
<form action="" method="POST" novalidate>

<fieldset class="uk-fieldset">

<legend class="uk-legend uk-text-uppercase">Add New Post</legend>

@if(session()->has('message'))

<div class="uk-alert-success" uk-alert>
<a class="uk-alert-close" uk-close></a>
<p><strong>{{ session()->get('message') }}</strong></p>
</div>

@endif

<div class="uk-margin">
<label class="uk-text-bold">Post Title</label>
<input class="uk-input" type="text" placeholder="Post title" name="title" value="{{ old('title') ?? $data->title }}">
</div>

<div class="uk-margin">
<label class="uk-text-bold">Post Content</label>
<textarea class="uk-textarea" rows="5" placeholder="Write here..." name="content">{{ old('content') ?? $data->content }}</textarea>
</div>

@if ($errors->any())
<div class="uk-alert-danger" uk-alert>
<a class="uk-alert-close" uk-close></a>
@foreach ($errors->all() as $error)
<p>{{ $error }}</p>
@endforeach
</div>
@endif

<div class="uk-margin">
<button class="uk-button uk-button-primary" type="submit">Update</button>
</div>

</fieldset>
@csrf
</form>
<!-- END OF EDIT FORM -->
</div>

</body>
</html>

Creating model and migration

After creating views now we will create a Post model and the model migration. To do this run the below command.

Make sure that the app folder is selected on your terminal.

php artisan make:model Post -m

After that open migrations folder which is inside the database folder and then open xxxx_xxxx_xx_xxxxxx_create_posts_table.php

Now in the posts schema you need to add two columns – title and content

Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('content');
            $table->timestamps();
});

After adding the two column now run the below command to run all of your migrations –

php artisan migrate

If you get an error (specified key was too long) then open the database.php file which is inside your config folder.

Then change the charset and collection value of mysql connection to –

'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',

After that run the below command –

php artisan migrate:fresh

Make controller

Now time to make PostController but before we create the PostController we will create routes –

To create routes open the web.php which is inside the routes folder –

web.php

<?php
// HOME PAGE
Route::get('/', '[email protected]');
// INSERT POST
Route::post('/', '[email protected]');
// EDIT POST
Route::get('/edit/{id}', '[email protected]');
// UPDATE POST
Route::post('/edit/{id}', '[email protected]');
// DELETE POST
Route::get('/delete/{id}', '[email protected]');

Making PostController

To make Post Controller you need to run the below command

php artisan make:controller PostController

After creating the Post Controller now open the Post Controller but where is the Post Controller? you can find the PostController by following the image –

Find the laravel controllers

PostController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

// Declared the Post model
use App\Post;

class PostController extends Controller
{
    public function index(){
        // FETCH ALL POSTS
        $data = Post::all();
        // RETURN INDEX VIEW WITH ALL POSTS
        return view('index',compact('data'));
    }

    public function insert(){
        // VALIDATE REQUEST DATA
        $data = request()->validate([
            'title' => 'required',
            'content' => 'required'
        ]);
        // INSERTING POST
        Post::create($data);
        // THEN REDIRECT TO HOME PAGE
        return redirect('/');
    }

    public function edit($id){
        // FETCH POST WITH SPECIFIC ID
        $data = Post::where('id',$id)->firstOrFail();
        // RETURN EDIT VIEW WITH THE POST
        return view('edit', compact('data'));
    }

    public function update($id){
        // VALIDATE REQUEST DATA
        $data = request()->validate([
            'title' => 'required',
            'content' => 'required'
        ]);
        // UPDATE POST
        Post::where('id',$id)->update($data);
    
        return redirect('/edit/'.$id)->with('message','Post updated successfully');

    }

    public function delete($id){
       // DELETE POST BY SPECIFIC ID 
        $dlete = Post::findOrFail($id);
        $dlete->delete();
        return redirect('/');
    }
}

After that open the Post (Post.php) model which is inside your app folder and edit this Post model. we just set the $guarded property value to an empty array –

why we do this – Learn

Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $guarded = [];
}

Completed. Now run the Larave application by running the below command –

php artisan serve

open – http://localhost:8000

Posts Navigation


Leave a Reply

Your email address will not be published. Required fields are marked *