Home Laravel 9 Build Crud App with Laravel 11 and Vue.js

Build Crud App with Laravel 11 and Vue.js

15 min read
0
0
2,553

In this tutorial will teach Vue Laravel 10 CRUD using Vite step by step. Laravel  10 CRUD Application  we will cover about Create, Read, Update, and Delete and View crud operation in Laravel. Generate the Api is very easy task to transfer data using various front end applications like React,Vue,Angular etc.

 

Laravel is world best famous  PHP framework.it has various features. Laravel is a MVC architecture. crud using Laravel example I will show in the simple way to make eloquent Laravel crud application. Here is the best place where learn Laravel 10.laravel php used to create the web application very easy to create and hosting the application.

Installing Laravel 11

Create the new project which name is lbs-app.type by following command to create the Laravel project.

composer create-project laravel/laravel bbs-app

After Type the Command you have to wait until the project installation get  finish. After Finished it.let’s do the  setup on database.

Change .env File

Do the database configuration on  .env File for username, password and DB Name in this project i have changed the database name as bbs

After that run the project.

Run the Project

Run the Application using following command

php artisan serve

Create Migrations

In Laravel create the table called as Migration

Run the command to create the Migration

php artisan make:migration create_employees_table

After that you can check the inside  database folder migrations  create_employees_table file has been created
successfully.

Select and open the students table. add the following table fields employee,address,phone

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
  
    public function up(): void
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('address');
            $table->string('phone')->nullable();
            $table->timestamps();
        });
    }
 
    public function down(): void
    {
        Schema::dropIfExists('students');
    }
};

After modified the columns names  then run the migrate command to create the tables in the databases.before the run the
command please save project then run it.

php artisan migrate

Create Controller Api Controller

Create Controller  
in order to create the controller if it crud you can use  EmployeeController –api.

php artisan make:controller EmployeeController --api

here is the code snippet

<?php

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

class EmployeeController extends Controller
{
    protected $employee;
    public function __construct(){
        $this->employee = new Employee();
        
    }
    public function index()
    {

        try {
            return response()->json($this->employee->all(), 200);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Internal Server Error'], 500);
        }
     
    }
    
    public function store(Request $request)
    {  
        try {
            $employee = $this->employee->create($request->all());
            return response()->json($employee, 201);
        } catch (\Exception $e) {
            return response()->json(['error' => $e], 500);
        }
    }
  
    public function show(string $id)
    {
        try {
            $employee = $this->employee->find($id);
            if (!$employee) {
                return response()->json(['error' => 'Employee not found'], 404);
            }
            return response()->json($employee, 200);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Internal Server Error'], 500);
        }
    }
    public function update(Request $request, string $id)
    {
        try {
            $employee = $this->employee->find($id);
            if (!$employee) {
                return response()->json(['error' => 'Employee not found'], 404);
            }
            $employee->update($request->all());
            return response()->json($employee, 200);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Internal Server Error'], 500);
        }
    }
    public function destroy(string $id)
    {
        try {
            $employee = $this->employee->find($id);
            if (!$employee) {
                return response()->json(['error' => 'Employee not found'], 404);
            }
            $employee->delete();
            return response()->json(['message' => 'Employee deleted successfully'], 200);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Internal Server Error'], 500);
        }
    }
}

After create the controller need to create the model.

Create Model

Model is used to get the data from the database.

Create the Model name which is Employee

php artisan make:model Employee

After Model is Created the look like this. Code inside Model Class (app\Models\)

Change it as like this

Add the Namespace above

namespace App\Models;

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
  protected $table = 'employees';
  protected $primaryKey = 'id';
   protected $fillable = [
        'name',
        'address',
        'phone',
    ];
    use HasFactory;
}

Routes

Pages are Manage through routes. If you are crud system simple you can add it the routes one line look like this

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\EmployeeController;
Route::get('/', function () {
    return view('welcome');
});

Route::apiResource('/employee', EmployeeController::class);

APi Route Creation

php artisan install:api

List the Routes

php artisan route:list

API Test URL

Install Vue

going to install the vue go to the respective website which is https://vuetifyjs.com/

npm create vuetify@latest

After Create the Components folder. inside the folder create the file as Student.jsx.

Install axois

npm i redaxois

Employee.vue

Paste the following code snippet

<template>
      <div class="container">
          <h3 align="center" class="mt-5">Employee Management</h3>
          <div class="row">
              <div class="col-md-2">
              </div>
              <div class="col-md-8">
              <div class="form-area">
                <form @submit.prevent="save" id="check-register-form">
                   
                      <div class="row">
                          <div class="col-md-6">
                            <label>Employee Name</label>
                            <v-text-field
                            v-model="employee.name"
                            label="Employee Name"
                            required>
                           </v-text-field>
                          </div>

                          <div class="col-md-6">
                              <label>Employee Address</label>
                              <v-text-field
                              v-model="employee.address"
                              label="Employee Address"
                              required>
                             </v-text-field>
                          </div>
                      </div>
                      <div class="row">
                          <div class="col-md-12">
                              <label>Phone</label>
                              <v-text-field
                              v-model="employee.phone"
                              label="Employee Address"
                              required>
                             </v-text-field>
                            
                          </div>
                      </div>
                      <div class="row">
                          <div class="col-md-12 mt-3">

                            <v-btn type="submit" color="success" form="check-register-form">Save</v-btn>


                          </div>
                      </div>
                  </form>
              </div>

              <v-table theme="dark">
                <thead>
                  <tr>
                    <th class="text-left">
                      Employee ID
                    </th>
                    <th class="text-left">
                      Employee Name
                    </th>

                    <th class="text-left">
                      Address
                    </th>

                    <th class="text-left">
                      Phone
                    </th>
                    <th class="text-left">
                      Action
                    </th>


                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="employee in result"
                    :key="employee.id"
                  >
                   <td>{{ employee.id }}</td>
                    <td>{{employee.name }}</td>
                    <td>{{ employee.address }}</td>
                    <td>{{ employee.phone }}</td>
                    <td>
                    <v-btn type="button" color="info"  @click="edit(employee)">Edit</v-btn>
                            
                            <v-btn type="button" color="danger"  @click="remove(employee)">Delete</v-btn>
                          </td>        
                  </tr>
                </tbody>
              </v-table>
              
              </div>
          </div>
      </div>

 
</template>


<script>


 
import axios from 'redaxios';



  export default {
    name: 'Employee',
    data () {
      return {
        result: {},
        employee:{
                   id: '',
                   name: '',
                   address: '',
                   phone: ''
 
 
        }
      }
    },
    created() { 
        this.EmployeeLoad();
    },
    mounted() {
          console.log("mounted() called.......");
         
      },
 
    methods: {
      EmployeeLoad()
           {
                 var page = "http://127.0.0.1:8000/api/employee";
                 axios.get(page)
                  .then(
                      ({data})=>{
                        console.log(data);
                        this.result = data;
                      }
                  );
           },
           
          
           save()
           {
            if(this.employee.id == '')
              {
                this.saveData();
              }
              else
              {
                this.updateData();
              }       
 
           },
           saveData()
           {
            axios.post("http://127.0.0.1:8000/api/employee", this.employee)
            .then(
              ({data})=>{
                this.EmployeeLoad();
                 this.employee.name = '';
                  this.employee.address = '',
                  this.employee.phone = ''
                   this.id = ''
              }
            )
 
           },
           edit(employee)
           {
            this.employee = employee;
           
           },
           updateData()
           {
              var editrecords = 'http://127.0.0.1:8000/api/employee/'+ this.employee.id;
              axios.put(editrecords, this.employee)
              .then(
                ({data})=>{
                  this.employee.name = '';
                  this.employee.address = '',
                  this.employee.phone = ''
                  this.id = ''
                  alert("Updated!!!");
                  this.EmployeeLoad();
                }
              );
 
           },
 
           remove(employee){
 
             var url = `http://127.0.0.1:8000/api/employee/${employee.id}`;
 

              axios.delete(url);
              alert("Deleteddd");
              this.EmployeeLoad();
            }
      }
  }
  </script>

<style scoped>
        .form-area{
          padding: 20px;
          margin-top: 20px;
            background-color:#0b0b0b;
            color: #fffcfc;
        }
        .bi-trash-fill{
          color:red;
          font-size: 18px;
        }
        .bi-pencil{
          color:green;
          font-size: 18px;
          margin-left: 20px;
        }



</style>

App.vue

<script setup>
import Student from './components/Employee.vue'
</script>

<template>
  
  <Employee/>
</template>

i have attached the video link below. which will do this tutorials step by step.

 

Load More Related Articles
Load More By admin
Load More In Laravel 9

Leave a Reply

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

Check Also

Inventory management system using React

In today’s fast-paced business environment, an efficient inventory management system…