Home Angular Laravel 10 Angular Complete Crud Application

Laravel 10 Angular Complete Crud Application

16 min read
0
0
3,427

In this tutorial will teach React JS 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 10

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

composer create-project laravel/laravel lbs-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 lbs

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_students_table

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

Select and open the students table. add the following table fields stname,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->date('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  StudentController –api.

php artisan make:controller StudentController --api

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 Student

php artisan make:model Student

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 = 'students';
  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\StudentController;
Route::get('/', function () {
    return view('welcome');
});

Route::apiResource('/student', StudentController::class);

List the Routes

php artisan route:list

After created the controller paste this following code snippet

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employee;
class EmployeeController extends Controller
{
    protected $student;
    public function __construct(){
        $this->student = new Student();
        
    }
    public function index()
    {
        return $this->student->all();
     
    }
    
    public function store(Request $request)
    {
     return $this->student->create($request->all());
    
       
    }
  
    public function show(string $id)
    {
     $student = $this->student->find($id);  
    }

    public function update(Request $request, string $id)
    {
         $student = $this->student->find($id);
         $student->update($request->all());
         return $student;
    }
    public function destroy(string $id)
    {
     $student = $this->student->find($id);
    return $student->delete();   
    }
}

API Test URL

Angular

Angular is a front-end application we have already created the folder front end inside the folder open the command prompt and type the commands.

Installing Angular CLI

npm install -g @angular/cli

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

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

Bootstrap implementation

copy the bootstrap style from the respective bootstrap website and paste the code inside the index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyFrontendApp</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

//Bootstrap
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

</head>

<body>
  <app-root></app-root>
</body>
</html>
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule} from '@angular/forms';


import { HttpClientModule } from '@angular/common/http';
import { StudentComponent } from './student/student.component';
@NgModule({
  declarations: [
    AppComponent,
    StudentComponent

  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    
    FormsModule,

    HttpClientModule,
   
 
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

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

student.compoent.html

<div class="container mt-4" >
 
    <div class="card">
            <h1>Student 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>Phone</label>
            <input type="text" [(ngModel)]="phone" [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>Student</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">Phone</th>
                <th scope="col">Option</th>
              </tr>
            </thead>
            <tbody>
                <tr *ngFor="let StudentItem of StudentArray">
     
                <th scope="row">{{StudentItem.id  }}</th>
                <td>{{StudentItem.name  | uppercase}}</td>
                <td>{{StudentItem.address }}</td>
                <td>{{StudentItem.phone }}</td>
     
                <td>
                  <button type="button" class="btn btn-success" (click)="setUpdate(StudentItem)">Edit</button>
                  
                  <button type="button" class="btn btn-danger" (click)="setDelete(StudentItem)">Delete</button>
                
                </td>
              </tr>
              
            </tbody>
          </table>
     
     
        </div>

student.component.ts

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

@Component({
  selector: 'app-student',
  templateUrl: './student.component.html',
  styleUrls: ['./student.component.scss']
})
export class StudentComponent {

  StudentArray : any[] = [];
  isResultLoaded = false;

 
  
  name: string ="";
  address: string ="";
  phone: Number =0;
 
  currentStudentID = "";


constructor(private http: HttpClient )
  {
    this.getAllStudent();
 
  }

  getAllStudent()
  {
    
    this.http.get("http://127.0.0.1:8000/api/student")
  
    .subscribe((resultData: any)=>
    {
        this.isResultLoaded = true;
        console.log(resultData);
        this.StudentArray = resultData;
    });
  }
 
  register()
  {
  
    let bodyData = {
      "name" : this.name,
      "address" : this.address,
      "phone" : this.phone
    };
 
    this.http.post("http://127.0.0.1:8000/api/student",bodyData,{responseType: 'text'}).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Student Registered Successfully");
        this.getAllStudent();
        this.name = '';
        this.address = '';
        this.phone  = 0;
    });
  }
  setUpdate(data: any)
  {
   this.name = data.name;
   this.address = data.address;
   this.phone = data.phone;
   this.currentStudentID = data.id;
  }
 
  UpdateRecords()
  {
    let bodyData = {
      "id" : this.currentStudentID,
      "name" : this.name,
      "address" : this.address,
      "phone" : this.phone,
  
    };
    
    this.http.put("http://127.0.0.1:8000/api/student"+ "/"+ this.currentStudentID,bodyData).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Student Registered Updateddd")
        this.getAllStudent();
      
    });
  }
 
  save()
  {
    if(this.currentStudentID == '')
    {
        this.register();
    }
      else
      {
       this.UpdateRecords();
      }      
 
  }
 
  setDelete(data: any)
  {
    
    
    this.http.delete("http://127.0.0.1:8000/api/student"+ "/"+ data.id,{responseType: 'text'}).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Student Deleteddd")
        this.getAllStudent();
        this.name = '';
        this.address = '';
        this.phone  = 0;
  
    });
 
  }



}

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 Angular

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…