Angular and Laravel authentication

Signup and Login using angular & laravel

Create Laravel application

composer create-project laravel/laravel backend

Enter in your project directory using cd

cd backend

Open your project in code editor using cmd command

code .

Create Db

Set credentials in .env

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

Install laravel JWT

composer require tymon/jwt-auth or (composer require tymon/jwt-auth –-ignore-platform-reqs  

Add service provider (jwtauth class)

Add the service provider to the providers array in the config/app.php config file as follows:

'providers' => [
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,

Run the following command to publish the package config file:

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

Generate jwt secret key : run below artisan command

php artisan jwt:secret

Inside .env it will add using above command

In user model implement jwtsubject class and add getJWTIdentifier(), getJWTCustomClaims() and setPasswordAttribute functions

app\Models\User.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Tymon\JWTAuth\Contracts\JWTSubject;

use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;

class User extends Authenticatable implements JWTSubject
{
    use HasApiTokens, HasFactory, Notifiable;

    use HasProfilePhoto;
    use TwoFactorAuthenticatable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'fb_id',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    public function setPasswordAttribute($value){
        return $this->attributes['password'] = bcrypt($value);
    }
}

Inside config/auth.php replace guard

'defaults' => [
        //'guard' => 'web', // replace it with api 'guard' => 'api',
        'guard' => 'api',
        'passwords' => 'users',
    ],

And add api guard (config/auth.php)

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],

Create AuthController

Php artisan make:controller AuthController

Migrate tables

php artisan migrate

Create signup route in api.php

use App\Http\Controllers\AuthController;

Route::post('signup',[AuthController::class,'signup']);

Create signup method in AuthController

public function signup(Request $request){        
        $userData = User::create($request->except('pasword_confirmation'));
        return response()->json(['message'=>"User Added", 'userData'=>$userData,"statusCode"=>200]);
    }

Run laravel application

php artisan serve

Run signup api in postman

http://127.0.0.1:8000/api/signup

Check user table in DB

Create login route in api.php

Route::post('login',[AuthController::class,'login']);

Create login and respondtoken function in AuthController

public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Failed Email or Password not matches!!'], 401);
        }

        return $this->respondWithToken($token);
    }
public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }

Run http://127.0.0.1:8000/api/login with user credentials in ajax format with postman

Backend API we have created, now we will call these API using angular so first install angular and create new application

Create frontend application using ng new command

 ng new frontend
cd frontend

Run frontend application using Command Prompt

ng serve  or  ng serve --o

Access url http://localhost:4200/ in browser

You will get default angular front page

Install bootstrap

ng add @ng-bootstrap/ng-bootstrap

Create a navbar component using below command

ng g c components/navbar

Inside the app.component.html replace the content with

<app-navbar></app-navbar>
<div class="container">
  <router-outlet></router-outlet>
</div>

And re-run app using “ng serve”

Create login and signup component

ng g c components/login
ng g c components/signup

Create routes inside app-routing-module

src\app\app-routing.module.ts

import { LoginComponent } from './components/login/login.component';
import { SignupComponent } from './components/signup/signup.component';

const routes: Routes = [
  {path:'login',component:LoginComponent},
  {path:'signup',component:SignupComponent},
  {path:'',redirectTo:'/signup',pathMatch:'full'}
];

Create profile component

ng g c components/profile

Add profile route in app-routing.module.ts file

import { LoginComponent } from './components/login/login.component';
import { ProfileComponent } from './components/profile/profile.component';
import { SignupComponent } from './components/signup/signup.component';

const routes: Routes = [
  {path:'login',component:LoginComponent},
  {path:'signup',component:SignupComponent},
  {path:'profile',component:ProfileComponent},
  {path:'',redirectTo:'/signup',pathMatch:'full'}
];

Create navbar html

<nav class="navbar navbar-expand-lg bg-light">
    <div class="container-fluid">
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarTogglerDemo03">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" routerLink="login">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" routerLink="login">Login</a>
          </li>
          <li class="nav-item">
            <a class="nav-link"  routerLink="signup" >Register</a>
          </li>
          <li class="nav-item">
            <a class="nav-link"  routerLink="profile" >Profile</a>
          </li>

        </ul>
        
      </div>
    </div>
  </nav>

Now check browser

Create a service for calling api

Now Create signup function in backend service

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

@Injectable({
  providedIn: 'root'
})
export class BackendService {

  constructor(private http:HttpClient) { }

  signUp(data:any){
    return this.http.post('http://127.0.0.1:8000/api/signup',data);
  }

}

Create SubmitSignUp function in signup.component.ts

import { Component, OnInit } from '@angular/core';
import {NgForm } from '@angular/forms';
import { BackendService } from 'src/app/services/backend.service';
@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {
  public form={
    name:null,
    email:null,
    password:null,
    cpassword:null
  }
  public error:any=[];
  constructor(private backend:BackendService) { }

  ngOnInit(): void {
  }

  submitSignup(registrationForm:NgForm){
     return this.backend.signUp(this.form).subscribe(
      // data=>console.log(data),
       data=>this.handleResponse(data,registrationForm),
       error=>this.handleError(error),
     );
   }
   handleResponse(data:any,registrationForm:any){
    if (data.statusCode === 200) {
      registrationForm.resetForm(); 
      }
   }
   handleError(error:any){
    this.error = error.error.errors;
   }

}

Add Signup form in signup.component.html

<nav class="navbar navbar-expand-lg bg-light">
    <div class="container-fluid">
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarTogglerDemo03">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" routerLink="login">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" routerLink="login">Login</a>
          </li>
          <li class="nav-item">
            <a class="nav-link"  routerLink="signup" >Register</a>
          </li>
          <li class="nav-item">
            <a class="nav-link"  routerLink="profile" >Profile</a>
          </li>

        </ul>
        
      </div>
    </div>
  </nav>

Now check Signup URL in browser

http://localhost:4200/signup

Import httpClientModule in app.module.ts file (src\app\app.module.ts)

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { NavbarComponent } from './components/navbar/navbar.component';
import { SignupComponent } from './components/signup/signup.component';
import { HttpClientModule} from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    SignupComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgbModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Import FormsModule in app.modules.ts

import { FormsModule } from '@angular/forms';

imports: [
FormsModule

Add Success alert in signup.html

 <div class="row"  *ngIf="msg">
            <div class="col-xs-12">
              <p class="alert alert-success">
                  <strong>Registration Success!</strong> 
                  <span routerLink="/login"> Please click here to login!. </span>    
              </p>
            </div>
          </div>

Add  [ngModel] for every field and disable submit button until form fields are blank

[(ngModel)]="form.name"
[(ngModel)]="form.email"
[(ngModel)]="form.email"
[(ngModel)]="form.password"
[(ngModel)]="form.cpassword"
[disabled]="!registrationForm.valid"

Complete Sign up form code

<div class="col-8">
  <div class="card">
      <div class="card-header">
          Register Here
      </div>
      <div class="card-body">

        <div class="row"  *ngIf="msg">
          <div class="col-xs-12">
            <p class="alert alert-success">
                <strong>Registration Success!</strong> 
                <span routerLink="/login"> Please click here to login!. </span>    
            </p>
          </div>
        </div>

          <form #registrationForm="ngForm" (ngSubmit)="submitSignup(registrationForm)">
              <div class="mb-3">
                  <label for="name" class="form-label">Name </label>
                  <input type="text" class="form-control" id="name" name="name" [(ngModel)]="form.name" required>                   
                </div>
              <div class="mb-3">
                <label for="email" class="form-label">Email address</label>
                <input type="email" class="form-control" id="email" name="email" [(ngModel)]="form.email" required>
               
              </div>

              <div class="mb-3">
                <label for="password" class="form-label">Password</label>
                <input type="password" class="form-control" id="password" name="password" [(ngModel)]="form.password" required>
              </div>
              
              <div class="mb-3">
                  <label for="cpassword" class="form-label">Confirm Password</label>
                  <input type="password" class="form-control" id="cpassword" name="cpassword" [(ngModel)]="form.cpassword" required>
                </div>
              <button type="submit" class="btn btn-primary" [disabled]="!registrationForm.valid">Submit</button>
            </form>
      </div>
  </div>
</div>

Now run ng serve and access URL

Submit signup form

Add login form in login.component.html

src\app\components\login\login.component.html

<div class="col-8">
    <div class="card">
        <div class="card-header">
            Login Here
        </div>
        <div class="card-body">
            <form>
                <div class="mb-3">
                  <label for="email" class="form-label">Email address</label>
                  <input type="email" class="form-control" id="email" name="email"  required>
                 
                </div>
                <div class="mb-3">
                  <label for="password" class="form-label">Password</label>
                  <input type="password" class="form-control" id="password" name="password"  required>
                </div>
                
                <button type="submit" class="btn btn-primary">Submit</button>
              </form>
        </div>
    </div>
</div>

Create login function in backendservice.ts

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

@Injectable({
  providedIn: 'root'
})
export class BackendService {

  constructor(private http:HttpClient) { }

  signUp(data:any){
    return this.http.post('http://127.0.0.1:8000/api/signup',data);
  }

  login(data:any){
    return this.http.post('http://127.0.0.1:8000/api/login',data);
  }
}

Import and declare LoginComponent in app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { NavbarComponent } from './components/navbar/navbar.component';
import { LoginComponent } from './components/login/login.component';
import { SignupComponent } from './components/signup/signup.component';
import { FormsModule } from '@angular/forms';
import { HttpClientModule} from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,

Import backend service in login component and create object in constructor function

import { BackendService } from 'src/app/services/backend.service';
constructor(private backend:BackendService) { }

Define form with used fields

public form = {
    email:null,
    password:null
  }

Create token service

ng g s services/token
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class TokenService {

  constructor() { }

  handle(token:any){
    this.set(token);
  }

  set(token:any){
    return localStorage.setItem('token',token);
  }

  get(){
    return localStorage.getItem('token');
  }

  remove(){
    return localStorage.removeItem('token');
  }

  isValid(){
    const token = this.get();
    if(token){
      const payload = this.payload(token);
      if(payload){
        return (payload.iss==="http://127.0.0.1:8000/api/login")?true:false;
      }
    }
    return false;
  }

payload(token:any){
    const payload = token.split('.')[1];
    return payload;
    //return this.decode(payload);
  }

  // decode(payload:any){
  //   return JSON.parse(atob(payload));
  // }

  loggedIn(){
    return this.isValid();
  }
}

Create auth service

ng g s services/auth
import { Injectable } from '@angular/core';
import { TokenService } from './token.service';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private loggedIn = new BehaviorSubject<boolean>(this.token.loggedIn());
  authStatus = this.loggedIn.asObservable();

  changeAuthStatus(value:boolean){
    this.loggedIn.next(value);
  }
  constructor(private token: TokenService) { }
}

Check is user logedIn or not

<li class="nav-item">
            <a class="nav-link" routerLink="login" *ngIf="!loggedIn">Login</a>
          </li>
          <li class="nav-item">
            <a class="nav-link"  routerLink="signup" *ngIf="!loggedIn">Register</a>
          </li>
          <li class="nav-item">
            <a class="nav-link"  routerLink="profile" *ngIf="loggedIn">Profile</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#" (click)="logout($event)" *ngIf="loggedIn">Logout</a>
          </li>

Complete Login HTML Code

<div class="col-8">
  <div class="card">
      <div class="card-header">
          Login Here
      </div>
      <div class="card-body">
          <form #loginForm="ngForm" (ngSubmit)="Login()">
              <div class="alert alert-danger" [hidden]="!error">
                  {{error}}
              </div>
              <div class="mb-3">
                <label for="email" class="form-label">Email address</label>
                <input type="email" class="form-control" id="email" name="email" [(ngModel)]="form.email" required>
               
              </div>
              <div class="mb-3">
                <label for="password" class="form-label">Password</label>
                <input type="password" class="form-control" id="password" name="password" [(ngModel)]="form.password" required>
              </div>
              
              <button type="submit" class="btn btn-primary" [disabled]="!loginForm.valid">Login</button>

              
            </form>

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

Now enter useremail and password press login button

Login Success

After user registration and login we will create CRUD steps

CRUD STEPS USING ANGULAR AND LARAVEL

Backend

Create ProjectController and model

php artisan make: controller ProjectsController --resource --model=Project

Create Route in api.php

use App\Http\Controllers\ProjectsController;
//projects
Route::resource('projects', ProjectsController::class);

Create Projects migration

php artisan make:migration create_projects_table

Add fields in migration file

$table->string('pname');
$table->string('ptype');
$table->string('ptechnology');

Run migration command

php artisan migrate

Check DB projects table created

Update Project Model

protected $fillable = [
        'pname','ptype','ptechnology'
    ];

Update ProjectsController

Fetch all project record and return using index function

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

Save project detail in DB using store function

$Project = new Project;
        $Project->pname       = $request->pname;
        $Project->ptype      = $request->ptype;
        $Project->ptechnology      = $request->ptechnology;
       
        $Project->save();
        return response()->json(['message'=>"Project Add Successfully...", 'Project'=>$Project,"statusCode"=>200]);

Show specified resource using show function

return response()->json($project);

Update project detail using update function

$Project->update($request->all());
        return response()->json(['message'=>"Project Update Successfully...", 'Project'=>$Project,"statusCode"=>200]);

And use delete function for delete particular record inside destroy()

$project->delete();

Complete code for ProjectController

<?php

namespace App\Http\Controllers;

use App\Models\Project;
use Illuminate\Http\Request;

class ProjectsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $Project= Project::all();
        return response()->json($Project);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $Project = new Project;
        $Project->pname       = $request->pname;
        $Project->ptype      = $request->ptype;
        $Project->ptechnology      = $request->ptechnology;
       
        $Project->save();
        return response()->json(['message'=>"Project Add Successfully...", 'Project'=>$Project,"statusCode"=>200]);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Project  $project
     * @return \Illuminate\Http\Response
     */
    public function show(Project $project)
    {
        return response()->json($project);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Project  $project
     * @return \Illuminate\Http\Response
     */
    public function edit(Project $project)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Project  $project
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Project $project)
    {
        

        $Project->update($request->all());
        return response()->json(['message'=>"Project Update Successfully...", 'Project'=>$Project,"statusCode"=>200]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Project  $project
     * @return \Illuminate\Http\Response
     */
    public function destroy(Project $project)
    {
        $project->delete();
    }
}

You can test Project API using postman

Create Project using postman

View all Project API

View Particular Project

Delete Project

Update Project

Steps for Frontend (Angular)

Create a project component using below command

ng g c components/project

Import Project Component inside app-routing-modules and create projects route in Routes array

import { ProjectComponent } from './components/project/project.component';
const routes: Routes = [
{path:'projects',component:ProjectComponent},

Create Project tab in navbar

<li class="nav-item">
    <a class="nav-link"  routerLink="projects" *ngIf="loggedIn">Project</a>
</li>

Services

Create project “Submit”, ”Update”, ”Fetch” and ,”Delete” functions Inside backend service for calling backend services.

src\app\services\backend.service.ts

submitProject(data:any){
    return this.http.post('http://127.0.0.1:8000/api/projects',data);
  }

  updateProject(id:any,data:any){
    return this.http.put('http://127.0.0.1:8000/api/projects/'+id,data);
  }
  
  fetchAllProjects(){
    return this.http.get('http://127.0.0.1:8000/api/projects');
  }

  deleteProject(id:any){
    return this.http.delete('http://127.0.0.1:8000/api/projects/'+id);
  }

  fetchProjectRecord(id:any){
    return this.http.get('http://127.0.0.1:8000/api/projects/'+id);
  }

Project Component

Import NgForm and BackendService jn project component

src\app\components\project\project.component.ts

import { NgForm } from '@angular/forms';
import { BackendService } from 'src/app/services/backend.service';

Declair form object and variables

export class ProjectComponent implements OnInit {
  isEdit:boolean=false;
  isID:boolean=false;
  title:string="Add";
  button:string="Submit";
  public form={
    pname:"",
    ptype:"",
    pwave:"",
    psquad:"",
    ptechnology:""

  }

Create backend service object in constructor and create variables

constructor(private backendService:BackendService) { }
  public error:any = [];
  public msg: any = null;
  public updatemsg:any = null;
  public getProjectData:any = [];
  public getProjectRecord:any =[];

Create fetchAllProject function and call it using ngOnInIt, using it we are calling service function (backendService.fetchAllProjects) and that service function is calling backend API for calling all project to DB.

ngOnInit(): void {
    this.fetchAllProjects();
  }

  fetchAllProjects(){
    return this.backendService.fetchAllProjects().subscribe(
       data=>this.getProjectData=data,
       error=>this.error = error.error.errors,
     );
  }

Now create SubmitProject function in project component ts file for submit project functionality

submitProject(projectSubmitForm:NgForm){
      return this.backendService.submitProject(this.form).subscribe(
        // data=>console.log(data),
         data=>this.handleResponse(data,projectSubmitForm),
         error=>this.handleError(error),
       );
  }
 handleResponse(data:any,projectSubmitForm:any){
    if (data.statusCode === 200) {
      projectSubmitForm.resetForm();
      this.msg = 'success';
      this.fetchAllProjects();
      }
  }

  handleError(error:any){
    this.error = error.error.errors;
  }

For Project delete create deleteProject function

deleteProject(id:any){
    return this.backendService.deleteProject(id)
        .subscribe(response => {
          alert("Record Delete Successfully");
          this.fetchAllProjects();
        });
  }

For edit project we will create editProject function , when user will click on edit button then we will call editProject function to show particular record data in form so user can edit and submit the form

editProject(id:any){
    this.isID=id;
    this.isEdit=true;
    this.title="Edit";
    this.button="Edit";
    return this.backendService.fetchProjectRecord(id).subscribe(
      data=>{
        this.getProjectRecord=data;
        this.form.pname=this.getProjectRecord.pname;
        this.form.ptype=this.getProjectRecord.ptype;
        this.form.pwave=this.getProjectRecord.pwave;
        this.form.psquad=this.getProjectRecord.psquad;
        this.form.ptechnology=this.getProjectRecord.ptechnology;
       // console.log("Fetch" + JSON.stringify(data))
      },
       error=>this.error = error.error.errors,
     );
  }

When user will click on update button record it should be updated for that we are using isEdit variable on edit click set it true, in submitProject function it will check isEdit value apply edit and submit functionality

submitProject(projectSubmitForm:NgForm){
    if(this.isEdit){
      // console.log("Update="+ JSON.stringify(this.form)+this.isID);
       return this.backendService.updateProject(this.isID,this.form).subscribe(
          data=>this.handleUpdateResponse(data,projectSubmitForm),
          error=>this.handleError(error),
        );
     }else{
      return this.backendService.submitProject(this.form).subscribe(
        // data=>console.log(data),
         data=>this.handleResponse(data,projectSubmitForm),
         error=>this.handleError(error),
       );
      }
  }

Project component complete code

import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { BackendService } from 'src/app/services/backend.service';

@Component({
  selector: 'app-project',
  templateUrl: './project.component.html',
  styleUrls: ['./project.component.css']
})
export class ProjectComponent implements OnInit {
  isEdit:boolean=false;
  isID:boolean=false;
  title:string="Add";
  button:string="Submit";
  public form={
    pname:"",
    ptype:"",
    ptechnology:""
  }

  constructor(private backendService:BackendService) { }
  public error:any = [];
  public msg: any = null;
  public updatemsg:any = null;
  public getProjectData:any = [];
  public getProjectRecord:any =[];

  ngOnInit(): void {
    this.fetchAllProjects();
  }

  fetchAllProjects(){
    return this.backendService.fetchAllProjects().subscribe(
       data=>this.getProjectData=data,
       error=>this.error = error.error.errors,
     );
  }

  submitProject(projectSubmitForm:NgForm){
    if(this.isEdit){
      // console.log("Update="+ JSON.stringify(this.form)+this.isID);
       return this.backendService.updateProject(this.isID,this.form).subscribe(
          data=>this.handleUpdateResponse(data,projectSubmitForm),
          error=>this.handleError(error),
        );
     }else{
      return this.backendService.submitProject(this.form).subscribe(
        // data=>console.log(data),
         data=>this.handleResponse(data,projectSubmitForm),
         error=>this.handleError(error),
       );
      }
  }

  handleUpdateResponse(data:any,projectSubmitForm:any){
    if (data.statusCode === 200) {
      this.updatemsg = 'success';
      this.fetchAllProjects();
      }
  }

  handleResponse(data:any,projectSubmitForm:any){
    if (data.statusCode === 200) {
      projectSubmitForm.resetForm();
      this.msg = 'success';
      this.fetchAllProjects();
      }
  }

  handleError(error:any){
    this.error = error.error.errors;
  }

  deleteProject(id:any){
    return this.backendService.deleteProject(id)
        .subscribe(response => {
          alert("Record Delete Successfully");
          this.fetchAllProjects();
        });
  }

  editProject(id:any){
    this.isID=id;
    this.isEdit=true;
    this.title="Edit";
    this.button="Edit";
    return this.backendService.fetchProjectRecord(id).subscribe(
      data=>{
        this.getProjectRecord=data;
        this.form.pname=this.getProjectRecord.pname;
        this.form.ptype=this.getProjectRecord.ptype;
        this.form.ptechnology=this.getProjectRecord.ptechnology;
       // console.log("Fetch" + JSON.stringify(data))
      },
       error=>this.error = error.error.errors,
     );
  }

}

Project Component HTML

src\app\components\project\project.component.html

<h4>{{title}} Project</h4>

<div class="row" *ngIf="msg">
    <div class="col-xs-12">
      <p class="alert alert-success">
          <strong>Project Add Successfully!</strong>  
      </p>
    </div>
  </div>
  <div class="row" *ngIf="updatemsg">
    <div class="col-xs-12">
      <p class="alert alert-success">
          <strong>Project Updated Successfully!</strong>  
      </p>
    </div>
  </div>
  
<form #projectSubmitForm="ngForm" (ngSubmit)="submitProject(projectSubmitForm)" >
  <div class="input-group mb-3">
    <div class="input-group-prepend">
      <label class="input-group-text" for="pname">Project Name</label>
    </div>
    <input type="text" class="form-control" id="pname" name="pname" [(ngModel)]="form.pname" placeholder="Project Name">
  </div>

  <div class="input-group mb-3">
    <div class="input-group-prepend">
      <label class="input-group-text" for="ptype">Project Type</label>
    </div>
    <select class="custom-select form-control" id="ptype" name="ptype" [(ngModel)]="form.ptype">
        <option selected>Choose...</option>
        <option value="Medium">Medium</option>
        <option value="Large">Large</option>
        <option value="Extra Large">Extra Large</option>
      </select>
  </div>
  
  <div class="input-group mb-3">
    
    <div class="input-group-append">
      <label class="input-group-text" for="pwave">Select Wave</label>
    </div>
    <select class="custom-select form-control" id="pwave" name="pwave" [(ngModel)]="form.pwave">
        <option selected>Choose...</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        
      </select>
  </div>
  
  <div class="input-group mb-3">
    <div class="input-group-append">
      <label class="input-group-text" for="psquad">Select Squad</label>
    </div>
    <select class="custom-select form-control" id="psquad" name="psquad" [(ngModel)]="form.psquad">
        <option selected>Choose...</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
  </div>
  
  <div class="input-group mb-3">
    <div class="input-group-append">
      <label class="input-group-text" for="ptechnology">Select Technology</label>
    </div>
    <select class="custom-select form-control" id="ptechnology" name="ptechnology" [(ngModel)]="form.ptechnology">
        <option selected>Choose...</option>
        <option value="php">PHP</option>
        <option value="java">Java</option>
        
      </select>
  </div>
  <button type="submit" class="btn btn-primary">{{button}}</button>
  </form>


  <hr>

  <table class="table">
    <thead>
      <tr>
        <th scope="col">Sr</th>
        <th scope="col">Project Name</th>
        <th scope="col">Project Type</th>
        <th scope="col">Project Wave</th>
        <th scope="col">Project Squad</th>
        <th scope="col">Project Technology</th>
        <th scope="col">Action</th>

      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of getProjectData;let i = index;">
        <th scope="row">{{i+1}}</th>
        <td>{{item.pname}}</td>
        <td>{{item.ptype}}</td>
        <td>{{item.pwave}}</td>
        <td>{{item.psquad}}</td>
        <td>{{item.ptechnology}}</td>
        <td>
            <button type="button" class="btn btn-info" (click)="editProject(item.id)">Edit</button>&nbsp;
            <button type="button" class="btn btn-danger" (click)="deleteProject(item.id)">Delete</button>
        </td>
      </tr>
    </tbody>
  </table>

Complete Git Code

https://github.com/blogshub4/CRUD-Using-angular-and-laravel.git

Git for signup and login

https://github.com/blogshub4/SIGNUP-LOGIN-Using-ANGULAR-and-laravel.git

12 thoughts on “Angular and Laravel authentication

  • November 29, 2022 at 2:14 pm
    Permalink

    Thank you for sharing all the helpful information! It is extremely appreciated!

    Reply
  • November 29, 2022 at 5:31 pm
    Permalink

    It’s so nice to hear that you have a sense of humor that you share with your posts/blogs, ! Your posts have a great sense of humor. Thank you for the great tips!”

    Reply
  • November 30, 2022 at 2:08 pm
    Permalink

    Looking awesome, like always.

    Reply
  • January 24, 2024 at 5:12 am
    Permalink

    Tһis is really intereѕting, You are a very skilled bⅼogger.
    I have joined your rss feed and look forᴡard to seeking more of youг
    magnificent post. Also, I have ѕhaared your web site in my social networks!

    Reply
  • April 25, 2024 at 4:36 am
    Permalink

    Nice post.I learn something new and challenging on websites
    I stumbleupon every day. It will always be interesting to read through
    articles from other authors and practice something from their sites.

    Reply
  • May 20, 2024 at 11:49 am
    Permalink

    What’s up colleagues, good article and pleasant urging commented here, I am genuinely enjoying by these.

    Reply
  • July 5, 2024 at 2:14 pm
    Permalink

    Wow, this post has given me useful info and answered some of my questions. I hope to give something back and aid others like you helped me.

    Reply
  • August 21, 2024 at 10:37 am
    Permalink

    I have been browsing online more than three hours lately,
    but I never found any interesting article like yours.
    It’s beautiful value sufficient for me. In my opinion, if
    all web owners and bloggers made excellent content
    material as you did, the net will be much more useful than ever before.

    Reply

Leave a Reply

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