Laravel 8 CRUD Application

by Saimon Akram

laravel-8-crud

In this Post, i would like to show you laravel 8 crud operation example. we will implement a laravel 8 crud application for beginners. i will give you simple example of how to create crud in laravel 8. you will learn crud operation in laravel 8.So, let's follow few step to create example of laravel 8 crud application tutorial

Step 1 : Install Laravel 8:

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

Step 2: Database Configuration:

In second step, we will make database configuration for example database name, username, password etc for our crud application of laravel 8. So let's open .env file and fill all details like as bellow:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=crud
DB_USERNAME=root
DB_PASSWORD=

Step 3: Create Migration:

we are going to create crud application for contact. so we have to create migration for "contacts" table using Laravel 8 php artisan command, so first fire bellow command:

php artisan make:migration create_contacts_table

After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create contacts table.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=crud
DB_USERNAME=root
DB_PASSWORD=

Now you have to run this migration by following command:

php artisan migrate

Step 4: Add Routes:

Here, we need to add resource route for contacts crud application. so open your "routes/web.php" file and add following route.

routes/web.php

<?php


use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ContactController;



Route::get('/contact', [ContactController::class, 'index']);
Route::post('/contact/index', [ContactController::class, 'store']);
Route::get('/contact/create', [ContactController::class, 'create']);
Route::get('/contact/show/{id}', [ContactController::class, 'show']);
Route::delete('/contact/destroy/{id}', [ContactController::class, 'destroy']);
Route::get('/contact/edit/{id}', [ContactController::class, 'edit']);
Route::post('/contact/update/{id}', [ContactController::class, 'update']);

Step 5: Add Controller and Model:

In this step, now we should create new controller as ProductController. So run bellow command and create new controller. bellow controller for create resource controller.

php artisan make:controller ContactController --resource

After bellow command, you will find new file in this path "app/Http/Controllers/ContactController.php".

In this controller will create seven methods by default as bellow methods:

1)index()

2)create()

3)store()

4)show()

5)edit()

6)update()

7)destroy()

So, let's copy bellow code and put on ContactController.php file.

<?php


namespace App\Http\Controllers;
use App\Models\Contact;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;


class ContactController extends Controller
{
  
    public function index(Request $request)
    {
        $search= $request['search'] ?? "";
        if($search!=""){
            $contacts=Contact::where('book_name','LIKE',"%$search%")->simplepaginate(2);
        }
        else{
            //
            $contacts = Contact::simplepaginate(5);
        }
        // $contacts = Contact::simplepaginate(5);
      
   
      return view ('contacts.index',compact('contacts','search'));
    }


    
    public function create()
    {
        return view('contacts.create');
    }


   
    public function store(Request $request)
    {
        $rules=[
            'book_name'=> 'required',
            'image_file'=> 'required',
            'borrow_date'=> 'required',
            'return_date'=> 'required',
            'student_name'=> 'required|max:15',
            'member_type'=> 'required',
            'description'=> 'required|max:100',
            'academic_class'=> 'required',
        ];
        $cm=[
            'book_name.required'=>'Enter your name',
            
            'image_file.required'=>'please choose a image',
            'borrow_date.required'=>'Please insert your borrow date',
            'return_date.required'=>'Please insert your return date',
            'student_name.required'=>'Please insert your Name',
            'student_name.max'=>'your name must be at least 15 characters',
            'member_type.required'=>'Insert what kind of member you are!',
            'description.required'=>'Give a short Description of the book.',
            'description.max'=>'your description must be at least 100 characters',
            'academic_class.required'=>'Insert what class do you read!',
        ];


        $this->validate($request,$rules,$cm);


       
        $contact=new Contact();
        $contact->book_name=$request->book_name;
        $contact->image_file=$request->image_file;
        if($request->hasfile('image_file')) {
            $file=$request->file('image_file');
            $extension= $file->getClientOriginalExtension();
            $filename=time() . '.' . $extension;
            $file->move('uploads/contacts',$filename);
            $contact->image_file=$filename;



        }
        $contact->borrow_date=$request->borrow_date;
        $contact->return_date=$request->return_date;
        $contact->student_name=$request->student_name;
        $contact->member_type=$request->member_type;
        $contact->description=$request->description;
        $contact->academic_class=$request->academic_class;


       
        $contact->save();
        
      

        return redirect('/contact')->with('flash_message', 'Contact Addedd!');  
    }


    
    public function show($id)
    {
        $contact = Contact::find($id);
        return view('contacts.show')->with('contacts', $contact);
    }


    
    public function edit($id)
    {
        $contact = Contact::find($id);
        // // dd($contact);
        // return response()->json($contact);
        return view('contacts.edit')->with('contacts', $contact);
    }


  
    public function update(Request $request, $id)
    {
        
        
        $contact = Contact::find($id);
        
        $contact->book_name=$request->book_name;
        
        if($request->hasfile('image_file')) {
            echo $request->image_file;
            $destination= 'uplaods/contacts/'.$contact->image_file;
           echo $destination;
         
            if(File::exists($destination)){
                // dd($destination);
                File::delete($destination);
            }
            $file=$request->file('image_file');
            $extension= $file->getClientOriginalExtension();
            $filename=time() . '.' . $extension;
            $file->move('uploads/contacts',$filename);
            $contact->image_file=$filename;



        }
       
        // $contact->image_file=$request->image_file;
        $contact->borrow_date=$request->borrow_date;
        $contact->return_date=$request->return_date;
        $contact->student_name=$request->student_name;
        $contact->member_type=$request->member_type;
        $contact->description=$request->description;
        $contact->academic_class=$request->academic_class;


        $contact->update();
       
        // return redirect()->back()->with('flash_message', 'Book Info Updated!');  
        return redirect('/contact')->with('flash_message', 'Contact Updated!');  
    }


   
    public function destroy($id)
    {
        $deleteData= Contact::find($id);
        $deleteData->delete();
        // Contact::destroy($id);
        return redirect('/contact')->with('flash_message', 'Contact deleted!');  
    }
}

Ok, so after run bellow command you will find "app/Models/Contact.php" and put below content in Contact.php file:

<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


class Contact extends Model
{
    protected $table = 'contacts';
    protected $primaryKey = 'id';
    protected $fillable = ['book_name', 'image_file', 'borrow_date','return_date','student_name','member_type','description','academic_class'];
}


Step 6: Add Blade Files:

In last step. In this step we have to create just blade files. So mainly we have to create layout file and then create new folder "contacts" then create blade files of crud app. So finally you have to create following bellow blade file:

1) layout.blade.php

2) index.blade.php

3) create.blade.php

4) edit.blade.php

5) show.blade.php


So let's just create following file and put bellow code.

resources/views/contacts/layout.blade.php

<!DOCTYPE html>
<html>


<head>
    <title>Contact Laravel 8 CRUD</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>


<body>


    <div class="container">
        @yield('content')
    </div>


</body>


</html>


resources/views/contacts/index.blade.php

@extends('contacts.layout')
@section('content')
<div class="container">
    <div class="row">


        <div class="col-md-9 col-lg-12">
            <div class="card">
                <div class="card-header">Book Information</div>
                <div class="card-body">
                    <a href="{{ url('/contact/create') }}" class="btn btn-success btn-sm" title="Add New Contact">
                        <i class="fa fa-plus" aria-hidden="true"></i> Add New
                    </a>
                    <br />
                    <br />
                    <form action="" class="col-4" method="GET">
                     
                        .<div class="form-group">
                          
                          <input type="search" name="search" id="" value="{{$search}}" class="form-control" placeholder="Search" >
                         
                         
                        </div>
                        <button class="btn btn-primary">Search</button>
                        <a href="{{url('/contact')}}" class="btn btn-primary">Reset</a>
                    </form>
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                <th scope="col">S.No</th>
                                <th scope="col">Book Name</th>
                                <th scope="col">Book Image</th>
                                <th scope="col">Borrow Date</th>
                                <th scope="col">Return Date</th>
                                <th scope="col">Student Name</th>
                                <th scope="col">Member Type</th>
                                <th scope="col">Decscription</th>
                                <th scope="col">Academic Class</th>
                                <th scope="col">Action</th>
                                    {{-- <th>#</th>
                                    <th>Name</th>
                                    <th>Address</th>
                                    <th>Telephone</th>
                                    <th>Actions</th> --}}
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($contacts as $item)
                                <tr>
                                    <td>{{ $loop->iteration }}</td>
                                    <td>{{ $item->book_name }}</td>
                                    <td><img src="{{asset('uploads/contacts/' .$item->image_file )}}" alt="" width="100" height="100"srcset=""></td>
                                    <td>{{ $item->borrow_date }}</td>
                                    <td>{{ $item->return_date }}</td>
                                    <td>{{ $item->student_name }}</td>
                                    <td>{{ $item->member_type }}</td>
                                    <td>{{ $item->description }}</td>
                                    
                                    <td>{{ $item->academic_class }}</td>


                                    <td>
                                        <a href="{{ url('/contact/show/' . $item->id) }}" title="View Student"><button
                                                class="btn btn-info btn-sm"><i class="fa fa-eye" aria-hidden="true"></i>
                                                View</button></a>
                                        <a href="{{ url('/contact/edit/' . $item->id) }}"
                                            title="Edit Student"><button class="btn btn-primary btn-sm"><i
                                                    class="fa fa-pencil-square-o" aria-hidden="true"></i>
                                                Edit</button></a>


                                        <form method="POST" action="{{ url('/contact/destroy' . '/' . $item->id) }}"
                                            accept-charset="UTF-8" style="display:inline">
                                            {{ method_field('DELETE') }}
                                            {{ csrf_field() }}
                                            <button type="submit" class="btn btn-danger btn-sm" title="Delete Contact"
                                                onclick="return confirm(&quot;Confirm delete?&quot;)"><i
                                                    class="fa fa-trash-o" aria-hidden="true"></i> Delete</button>
                                        </form>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                        {{$contacts->links()}}
                    </div>


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


resources/views/contacts/create.blade.php

@extends('contacts.layout')
@section('content')


<div class="card">
    


        <div class="container my-4">



            <h2>Add A Book Information</h2>
            <form action="{{ url('/contact/index') }}" method="post" enctype="multipart/form-data">
                @csrf
                <div class="form-group">
                    <label for="book_name">Book Name</label>
                    <input type="text" class="form-control" id="book_name" name="book_name" aria-describedby="emailHelp">
                        @error('book_name')
                        <span class="text-danger">{{$message}}</span>
                        @enderror
                </div>
    
                <div class="form-group">
                    <label for="image_file">Book Image</label>
                    <input type="file" class="form-control" accept="image/*" name="image_file" id="image_file" >
                    
                        {{-- @error('image_file')
                        <span class="text-danger">{{$message}}</span>
                        @enderror --}}
                </div>
                <div class="form-group">
                    <label for="borrow_date">Borrow Date</label>
                    <input type="date" class="form-control" id="borrow_date" name="borrow_date" aria-describedby="emailHelp"
                        >
                        @error('borrow_date')
                        <span class="text-danger">{{$message}}</span>
                        @enderror
                </div>
                <div class="form-group">
                    <label for="return_date">Return-date</label>
                    <input type="date" class="form-control" id="return_date" name="return_date" aria-describedby="emailHelp"
                        >
                        @error('return_date')
                        <span class="text-danger">{{$message}}</span>
                        @enderror
                </div>
                <div class="form-group">
                    <label for="student_name">Student Name</label>
                    <input type="text" class="form-control" id="student_name" name="student_name"
                         >
                        @error('student_name')
                        <span class="text-danger">{{$message}}</span>
                        @enderror
                </div>
    
                <div class="form-group">
                    <label for="student_name">Member Type</label>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="member_type" id="member_type" value="Monthly"
                            >
                            @error('member_type')
                        <span class="text-danger">{{$message}}</span>
                        @enderror
                        <label class="form-check-label" for="member_type">
                            Monthly
                        </label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="member_type" id="member_type" value="Yearly"
                            checked >
                            @error('member_type')
                        <span class="text-danger">{{$message}}</span>
                        @enderror
                        <label class="form-check-label" for="member_type">
                            Yearly
                        </label>
                    </div>
                </div>
    
    
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea class="form-control" id="description" name="description" rows="3" ></textarea>
                    @error('description')
                        <span class="text-danger">{{$message}}</span>
                        @enderror
                </div>
                <div class="form-group">
                    <select class="form-select" name="academic_class" aria-label="Default select example">
                        <option selected>academic class</option>
                        <option value="5">Class 5</option>
                        <option value="6">class 6</option>
                        <option value="7">class 7</option>
                        <option value="8">class 8</option>
                        <option value="9">class 9</option>
                        <option value="10">class 10</option>
                        <option value="11">class 11</option>
                        <option value="12">class 12</option>
                    </select>
                </div>
                @error('academic_class')
                        <span class="text-danger">{{$message}}</span>
                        @enderror
                <button type="submit" name="submit" class="btn btn-primary my-3">Add Book Record</button>
            </form>
        </div>


    
</div>


@stop


resources/views/contacts/edit.blade.php

@extends('contacts.layout')
@section('content')


<div class="card">
    
    


      
        <div class="container my-4">



            <h2 class="my-3">Update A Book Information</h2>
            <form action="{{ url('/contact/update/' .$contacts->id) }}" method="post" enctype="multipart/form-data">
                @csrf
                <input type="hidden" name="id" id="id" value="{{$contacts->id}}" id="id" />
                
                <div class="form-group">
                    <label for="book_name">Book Name</label>
                    <input type="text" class="form-control" id="book_name" value="{{$contacts->book_name}}" name="book_name" 
                        required>
                </div>
    
                <div class="form-group">
                    <label for="image_file">Book Image</label>
                    <input type="file" class="form-control"  name="image_file"  required>
                    <img src="{{asset('uploads/contacts/' .$contacts->image_file )}}" alt="" width="100" height="100"srcset="">
                </div>
                <div class="form-group">
                    <label for="borrow_date">Borrow Date</label>
                    <input type="date" class="form-control" id="borrow_date" name="borrow_date" value="{{$contacts->borrow_date}}" aria-describedby="emailHelp"
                        required>
                </div>
                <div class="form-group">
                    <label for="return_date">Return-date</label>
                    <input type="date" class="form-control" id="return_date" name="return_date" value="{{$contacts->return_date}}" aria-describedby="emailHelp"
                        required>
                </div>
                <div class="form-group">
                    <label for="student_name">Student Name</label>
                    <input type="text" class="form-control" id="student_name" name="student_name" value="{{$contacts->student_name}}"
                        aria-describedby="emailHelp" required>
                </div>
    
                <div class="form-group">
                    <label for="student_name">Member Type</label>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="member_type" id="member_type" value="{{$contacts->member_type}}"
                            required>
                        <label class="form-check-label" for="member_type">
                            Monthly
                        </label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="member_type" id="member_type" value="{{$contacts->member_type}}"
                            checked required>
                        <label class="form-check-label" for="member_type">
                            Yearly
                        </label>
                    </div>
                </div>
    
    
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea class="form-control" id="description" name="description" value="{{$contacts->description}}" rows="3" required></textarea>
                </div>
                <div class="form-group">
                    <select class="form-select" name="academic_class" value="{{$contacts->academic_class}}" aria-label="Default select example" required>
                        <option selected>academic class</option>
                        <option value="5">Class 5</option>
                        <option value="6">class 6</option>
                        <option value="7">class 7</option>
                        <option value="8">class 8</option>
                        <option value="9">class 9</option>
                        <option value="10">class 10</option>
                        <option value="11">class 11</option>
                        <option value="12">class 12</option>
                    </select>
                </div>
                <button type="submit" name="submit" class="btn btn-primary my-3">Update Book Record</button>
            </form>
        </div>


    
</div>


@stop


resources/views/contacts/show.blade.php

@extends('contacts.layout')
@section('content')



<div class="card">
    <div class="card-header">Contactus Page</div>
    <div class="card-body">



        <div class="card-body">
            <h5 class="card-title">Name : {{ $contacts->book_name }}</h5>
            <p class="card-text">image : <img src="{{asset('uploads/contacts/' .$contacts->image_file )}}" alt="" width="100" height="100"srcset=""></p>
            <p class="card-text">Borrow Date : {{ $contacts->borrow_date }}</p>
            <p class="card-text">Return Date : {{ $contacts->return_date }}</p>
            <p class="card-text">Student Name : {{ $contacts->student_name }}</p>
            <p class="card-text">Member Type : {{ $contacts->member_type }}</p>
            <p class="card-text">Description : {{ $contacts->description }}</p>
            <p class="card-text">Academic class : {{ $contacts->academic_class }}</p>
        </div>


        </hr>


    </div>
</div>

Now we are ready to run our crud application example with laravel 8 so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/contact


Leave a Reply