Home Laravel 9 Laravel 9 Angular Crud Application

Laravel 9 Angular Crud Application

20 min read
0
0
2,637

This tutorial will teach you how to make simple Crud Application using Laravel 9 with Angular JS Frontend application using Api access crudapplication.

First Step What you have to do is you to divide the Front-End and Back-End.

Front-End – Vue JS

Back-End – Laravel 9

Create the folder myprojects. inside the folder frond end project you maintaing with the seperate folder.
backend project

Install Laravel 9

Create  a new Project type  the command on the command prompt  . I create the project name Office

type the command office-backend

composer create-project laravel/laravel office-backend

After Type the Command you have to wait till the project has been created. in this example i gave the project name as office-app. instead of that you have to give office-backend

after created the project you will get the success message i attached the screen shot below.

Second Step : You have to create the database so you have to go the mysql by typing the browser address bar http://localhost/phpmyadmin  then you will get the database dashboard after that you have to create the new database. I attached the screen shot image below.in this example i have create the database name is office.

after create the database.you have to open your project into Visual Studio Code Editor. after that you have to configure the database details into Laravel project .env file. i attach the database details below.

in this section DB-DATABASE  you have to give the name of the database which you have created.

After that run and check the application of the welcome screen of Laravel framework look like this.

Create Migration

Create the tables by typing this command

php artisan make:migration create_employees_table

After that inside  database folder create_employees_table.php  migrations  file has been created.  you can open the file.

Click and open the create_employees_table.php file. you can see by default look like this.

public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }

then you have to create the following fields.

$table->string(‘name’);

$table->string(‘address’);

$table->string(‘mobile’);

inside the function up() .function i shown in below clearly.

   public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('address');
            $table->string('mobile');
            $table->timestamps();
        });
    }

After that type the following command on the console.

php artisan migrate

the table has been created.you can check on the database.

Create Controller

Create the controller name which is EmployeeController

php artisan make:controller EmployeeController

after that open up the EmployeeController

EmployeeController

All view pages are manageable through the Controller. you have to add the Model namespace here

use App\Models\Employee  Data is coming from the database via the Model. Model is the part where communicate the with database to pass the data to the controller.

In the Employee Controller we have 4 different  functions(Index,Store,Update,destroy) shall able to perform  the Crud operations.

Lets Learn by On by One

index() Function : inside the index function we have written following codes.

$employees = Employee::all(); 
return response()->json($employees);

Employee::all(); in this code snippet describes get all the Employee details from Model Class which name is Employee and assign to $employees variable and pass as Json Format.

store() Function : public function store(Request $request) : in this code snippet describes when fill the form on the Front End(Vue JS) click Save button all the form data come and store variable $request.then set Form variable to database tables columns then assign to $employees variables.after that call $employees->save(); then record insert successfully get the response as json format.

public function store(Request $request)
    {
        $employees = new Employee([
            'name' => $request->input('name'),
            'address' => $request->input('address'),
            'mobile' => $request->input('mobile'),

        ]);
        $employees->save();
        return response()->json('Employee created!');
    }

Update() Function :  public function update(Request $request, $id) : in this code snippet describes when we make the changes of the  form on the Front End(Vue JS) click Save button all the form data come and store variable $request  along the $id variable. then set all the Form variable to database tables columns match with id find($id); variable.after that call $employees->update(); then record update successfully get the response as json format.

public function update(Request $request, $id)
    {
       $employees = Employee::find($id);
       $employees->update($request->all());
       return response()->json('Employee updated');
    }

destroy($id) Function  : public function destroy($id) in this code snippet describes when click the delete button on the table row of the Front End(Vue JS) application  get the id of row record and find($id); method to find the id. then delete the entire row records.

public function destroy($id)
    {
        $employees = Employee::find($id);
        $employees->delete();
        return response()->json(' deleted!');
    }

Full Code of the EmployeeController

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employee;

class EmployeeController extends Controller
{  
    public function index()
    {
        $employees = Employee::all();
        return response()->json($employees); 
    }   
    public function store(Request $request)
    {
        $employees = new Employee([
            'name' => $request->input('name'),
            'address' => $request->input('address'),
            'mobile' => $request->input('mobile'),
        ]);
        $employees->save();
        return response()->json('Employee created!');
    }
    public function show($id)
    {
        $contact = Employee::find($id);
        return response()->json($contact);
    }
    public function update(Request $request, $id)
    {
       $employees = Employee::find($id);
       $employees->update($request->all());
       return response()->json('Employee updated');
    }
    public function destroy($id)
    {
        $employees = Employee::find($id);
        $employees->delete();
        return response()->json(' deleted!');
    }
}

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

<?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', 'mobile'];   

    use HasFactory;
}

After that set Routes

go to the folder Routes inside folder select Routes file as api.php 

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\EmployeeController;


Route::get('/employees',[App\Http\Controllers\EmployeeController::class, 'index']);

Route::post('/save',[App\Http\Controllers\EmployeeController::class, 'store']);

Route::put('/update/{id}',[App\Http\Controllers\EmployeeController::class, 'update']);

Route::delete('/delete/{id}',[App\Http\Controllers\EmployeeController::class, 'destroy']);


Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Now BackEnd Part is Done. let’s start the Frond-End Part

Angular

Installing Angular CLI

npm install -g @angular/cli

After that create the new Project of Angular running by the following command

ng new office-frondend

Select the SCSS Style for Advanced CSS and Press Enter Key.

After complete the installation and run the project using following command.

ng serve

After that open the browser the paste the url .

Now you see the Angular Welcome Page.

After that open the Angular project into VS code editor.

now you can see the following file structure

Creating a new Component Employee Crud

ng g c employeecrud

Now you can see below employeecrud component has been created

After that install the Bootstrap by typing the following command

npm i bootstrap

After installed you have to set the path in to style.scss file

app.module.ts

FormModule
HttpClientModule  

add these module into the app.module.ts file  then only we will manage the forms and Http requests

After that open up the employeecrud.component.html

employeecrud.component.html

<div class="container mt-4" >

    <div class="card">
        <h1>Employee Registation</h1>

<form>
    <div class="form-group">
      <label>Name</label>
      <input type="text" [(ngModel)]="name" [ngModelOptions]="{standalone: true}" class="form-control" id="name" placeholder="Enter Name">

    </div>

    <div class="form-group">
        <label>address</label>
        <input type="text" [(ngModel)]="address" [ngModelOptions]="{standalone: true}" class="form-control" id="address" placeholder="Enter address">
  
      </div>

      <div class="form-group">
        <label>Mobile</label>
        <input type="text" [(ngModel)]="mobile" [ngModelOptions]="{standalone: true}" class="form-control" id="mobile" placeholder="Enter Mobile">
  
      </div>
    
    <button type="submit" class="btn btn-primary mt-4" (click)="save()" >Submit</button>
  </form>
</div>
<div>


    <div class="container mt-4" >

        <h1>Employee Table</h1>




    <table class="table">
        <thead>
         <h1 *ngIf="!isResultLoaded">Loading.................</h1>
         
        <tr>
            <th scope="col">ID</th>
            <th scope="col">Name</th>
            <th scope="col">Address</th>
            <th scope="col">Mobile</th>
            <th scope="col">Option</th>
          </tr>
        </thead>
        <tbody>
            <tr *ngFor="let EmployeeItem of EmployeeArray">

            <th scope="row">{{EmployeeItem.id  }}</th>
            <td>{{EmployeeItem.name  | uppercase}}</td>
            <td>{{EmployeeItem.address }}</td>
            <td>{{EmployeeItem.mobile }}</td>

            <td>
              <button type="button" class="btn btn-success" (click)="setUpdate(EmployeeItem)">Edit</button>
              
              <button type="button" class="btn btn-danger" (click)="setDelete(EmployeeItem)">Delete</button>
            
            </td>
          </tr>
          
        </tbody>
      </table>


    </div>

employeecrud.component.ts

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-employeecrud',
  templateUrl: './employeecrud.component.html',
  styleUrls: ['./employeecrud.component.scss']
})
export class EmployeecrudComponent implements OnInit {

  EmployeeArray : any[] = [];
  isResultLoaded = false;
  isUpdateFormActive = false;

  
  name: string ="";
  address: string ="";
  mobile: Number =0;

  currentEmployeeID = "";


  constructor(private http: HttpClient ) 
  {
    this.getAllEmployee();

  }

  ngOnInit(): void {
  }

  getAllEmployee()
  { 
    
    this.http.get("http://127.0.0.1:8000/api/employees")
  
    .subscribe((resultData: any)=>
    {
        this.isResultLoaded = true;
        console.log(resultData);
        this.EmployeeArray = resultData;
    });
  }

  register()
  {
   
    let bodyData = {
      "name" : this.name,
      "address" : this.address,
      "mobile" : this.mobile
    };

    this.http.post("http://127.0.0.1:8000/api/save",bodyData).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Employee Registered Successfully")
        this.getAllEmployee();
        this.name = '';
        this.address = '';
        this.mobile  = 0;
    });
  }

  setUpdate(data: any) 
  {
   this.name = data.name;
   this.address = data.address;
   this.mobile = data.mobile;
   this.currentEmployeeID = data.id;
  }

  UpdateRecords()
  {
    let bodyData = {
      "name" : this.name,
      "address" : this.address,
      "mobile" : this.mobile,
    };
    
    this.http.put("http://127.0.0.1:8000/api/update"+ "/"+ this.currentEmployeeID,bodyData).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Employee Registered Updateddd")
        this.getAllEmployee();
        this.name = '';
        this.address = '';
        this.mobile  = 0;
    });
  }



  save()
  {
    if(this.currentEmployeeID == '')
    {
        this.register();
    }
      else
      {
       this.UpdateRecords();
      }       

  }


  setDelete(data: any)
  {
    
    
    this.http.delete("http://127.0.0.1:8000/api/delete"+ "/"+ data.id).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Employee Deletedddd")
        this.getAllEmployee();
   
    });

  }
}

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

Employee Working Hours Calculation System using Java

Initialize the employee number, Hourswork,and Hoursrate to calculate a grosswage use the f…