CRUD Laravel Tutorial with Example From Scratch

CRUD Laravel Tutorial with Example From Scratch

Laravel CRUD tutorial with server side form validation example. Today, we’ll show you step by step how to perform crud operation with laravel application. In this tutorial, you will learn easy to insert update delete operation with laravel Application from scratch. This simple crud operation with laravel versions 5.8, 5.7 & 5.6.

In this article, you will learn very easy crud operation with laravel new latest version. I am going to show you crud operation in laravel latest version step by step from scratch

Contents

  • Install Laravel Fresh Project
  • Generate Model and Migration
  • Create Resource Route & Contoller
  • Create the blade view
  • Start Development Server
  • Conclusion

Install Laravel 5.7 Fresh Project

We need to install Laravel 5.7 fresh application using below command, Open your command prompt and run the below command :

composer create-project --prefer-dist laravel/laravel LaravelCrud

After successfully install laravel 5.7 Application, Go to your project .env file and set up database credential and move next step.

Configuration in .env

In this step, we will set database credential in .env file. Let’s open .env file.

 
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here

 Generate Model and Migration

Now we will create table name notes and it’s migration file. use the below command :

php artisan make:model Note -m

It command will create one model name Notes and also create one migration file for notes table. After successfully run the command go to database/migrations file and put the below here :

 
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateNotesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('notes', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('notes');
}
}

Next migrate the table using the below command.

php artisan migrate

If you found any query builder error in command prompt go to  => app\Providers\AppServiceProvider.php and put the below code here :

 use Illuminate\Support\Facades\Schema;
 
public function boot()
{
    Schema::defaultStringLength(191);
}

Now, add the fillable property inside Note.php file.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Note extends Model
{
  protected $fillable = [
    'title',
    'description',
  ];
}

Create Resource Route & Contoller

Create the NotesController using the below command.

php artisan make:controller NotesController --resource

This command will create contoller name NotesController and also inside by default seven methods like index,store,create,update,destroy,show,edit.

Next, We need to add the resource route. Go to routes/web.php put the below routes here :

<?php 

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

Route::resource('notes', 'NotesController');

Next open controller, Go to app/http/Controller/NotesController and put the below code here :

<?php
  
namespace App\Http\Controllers;
  
use App\Note;
use Illuminate\Http\Request;
use Redirect;
  
class NotesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data['notes'] = Note::paginate(10);
  
        return view('notes.list',$data);
    }
   
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('notes.create');
    }
  
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'description' => 'required',
        ]);
  
        Note::create($request->all());
   
        return Redirect::to('notes')
       ->with('success','Great! Note created successfully.');
    }
   
    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
    }
   
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {   
        $where = array('id' => $id);
        $data['note_info'] = Note::where($where)->first();

        return view('notes.edit', $data);
    }
  
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'title' => 'required',
            'description' => 'required',
        ]);
        
        $update = ['title' => $request->title, 'description' => $request->description];
        Note::where('id',$id)->update($update);
  
        return Redirect::to('notes')
       ->with('success','Great! Notes updated successfully');
    }
  
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Note::where('id',$id)->delete();
  
        return Redirect::to('notes')->with('success','Note deleted successfully');
    }
}

Create the blade view

We need to create some blade views files, Go to app/resources/views/ and create one folder name notes. Inside the notes folder Create the following blade files.

Create the notes folder. After successfully create notes folder than create 4 following blade files.

  1. Layout.blade.php
  2. List.blade.php
  3. Create.blade.php
  4. Edit.blade.php
Layout.blade.php

In this file put the below code here :

<!DOCTYPE html>
<html>
<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">
  <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel 5.7 CRUD Application With Example - Tutsmake.com</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
    <style>
    	.mt40{
    		margin-top: 40px;
    	}
    </style>
</head>
<body>
  
<div class="container">
    @yield('content')
</div>
   
</body>
</html>
List.blade.php
@extends('notes.layout')
 
@section('content')
<div class="row mt40">
   <div class="col-md-10">
   	<h2>Laravel 5.7 Crud Example - Tuts Make</h2>
   </div>
   <div class="col-md-2">
   	<a href="{{ route('notes.create') }}" class="btn btn-danger">Add Note</a>
   </div>
   <br><br>
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif
    @if ($errors->any())
    <div class="alert alert-danger">
        <strong>Opps!</strong> Something went wrong<br><br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
   @endif
	<table class="table table-bordered" id="laravel_crud">
	   <thead>
	      <tr>
	         <th>Id</th>
	         <th>Title</th>
	         <th>Description</th>
	         <th>Created at</th>
	         <td colspan="2">Action</td>
	      </tr>
	   </thead>
	   <tbody>
	      @foreach($notes as $note)
	      <tr>
	         <td>{{ $note->id }}</td>
	         <td>{{ $note->title }}</td>
	         <td>{{ $note->description }}</td>
	         <td>{{ date('d m Y', strtotime($note->created_at)) }}</td>
	         <td><a href="{{ route('notes.edit',$note->id)}}" class="btn btn- 
                  primary">Edit</a></td>
                 <td>
                <form action="{{ route('notes.destroy', $note->id)}}" method="post">
                  {{ csrf_field() }}
                  @method('DELETE')
                  <button class="btn btn-danger" type="submit">Delete</button>
                </form>
            </td>
	      </tr>
	      @endforeach
	   </tbody>
	</table>
	{!! $notes->links() !!}
</div>
@endsection
</div>
Create.blade.php
@extends('notes.layout')
  
@section('content')

<div class="row">
    <div class="col-lg-12 mt40">
        <div class="pull-left">
            <h2>Add Note</h2>
        </div>
    </div>
</div>
   
@if ($errors->any())
    <div class="alert alert-danger">
        <strong>Whoops!</strong> Something went wrong<br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
   
<form action="{{ route('notes.store') }}" method="POST" name="add_note">
    {{ csrf_field() }}
  
     <div class="row">
        <div class="col-md-12">
            <div class="form-group">
                <strong>Title</strong>
                <input type="text" name="title" class="form-control" placeholder="Enter 
                 Title">
            </div>
        </div>
        <div class="col-md-12">
            <div class="form-group">
                <strong>Description</strong>
                <textarea class="form-control" col="4" name="description" 
                 placeholder="Enter Description"></textarea>
            </div>
        </div>
        <div class="col-md-12">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>
   
</form>
@endsection
Edit.blade.php
@extends('notes.layout')
  
@section('content')

<div class="row">
    <div class="col-lg-12 mt40">
        <div class="pull-left">
            <h2>Update Note</h2>
        </div>
    </div>
</div>
   
@if ($errors->any())
    <div class="alert alert-danger">
        <strong>Opps!</strong> Something went wrong<br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
   
<form action="{{ route('notes.update', $note_info->id) }}" method="POST" name="update_note">
    {{ csrf_field() }}
    @method('PATCH')
  
     <div class="row">
        <div class="col-md-12">
            <div class="form-group">
                <strong>Title</strong>
                <input type="text" name="title" class="form-control" placeholder="Enter Title" value="{{ $note_info->title }}">
            </div>
        </div>
        <div class="col-md-12">
            <div class="form-group">
                <strong>Description</strong>
                <textarea class="form-control" col="4" name="description" placeholder="Enter Description" >{{ $note_info->description }}</textarea>
            </div>
        </div>
        <div class="col-md-12">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>
   
</form>
@endsection

Start Development Server

In this step, we will use the php artisan serve command . It will start your server locally

php artisan serve

If you want to run the project diffrent port so use this below command

php artisan serve --port=8080

If you want to remove public or public/index.php from URL In laravel, Click Me

Now we are ready to run our example so run bellow command to quick run.

http://localhost:8000/notes

Or direct hit in your browser

http://localhost/LaravelCrud /public/notes

Conclusion

In this article , We have successfully create Laravel 5.7 CRUD Application (Create, Read, Update, Delete) with example. Our examples run quickly.

You may like

  1. Laravel 6 Tutorial From Scratch | Step By Step
  2. Laravel 6 Ajax CRUD(DataTables Js) Tutorial Example
  3. Laravel 6 – Ajax CRUD (Operation) Application Example
  4. Laravel 6 CRUD Example Tutorial (Step By Step)
  5. Laravel 6 Angular JS CRUD Example Tutorial
Laravel crud example from scratch

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

7 replies to CRUD Laravel Tutorial with Example From Scratch

  1. it’s very simple example. keep it up tuts make

  2. Thanks, it works fine. I would like to use Dashboard how can i do?

  3. please give me solution for this

    • Please create a folder that is named notes and after that, you will create a list.blade.php file inside the notes folder.

  4. Dear Tuts Make,

    I have followed same step as you guide but showing welcome blade only. Not showing actual index page.

  5. Oh. great.
    My first working laravel project!
    Thank you.

  6. My first working laravel application.

Leave a Reply

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