Laravel and Angular: Creating a Full-Stack CRUD Application

To build a full-stack application using Laravel (PHP backend) and Angular (frontend), we will implement a basic CRUD (Create, Read, Update, Delete) application. In this example, the backend will manage a list of users, and the frontend will interact with this backend via HTTP requests.

Step 1: Backend - Laravel

1.1 Install Laravel

First, create a new Laravel project using Composer.

composer create-project --prefer-dist laravel/laravel laravel-angular-crud

After installing, navigate to the project directory:

cd laravel-angular-crud

1.2 Set Up Database

Create a MySQL database (e.g., laravel_angular_crud) and update the .env file in the root of your Laravel project to reflect the database connection.

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

Run the migration to set up the default tables (optional, for user authentication):

php artisan migrate

1.3 Create a Model and Migration for Users

Now, we’ll create a User model along with a migration file for the users table.

php artisan make:model User -m

Update the migration file (database/migrations/xxxx_xx_xx_create_users_table.php) to define the schema:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->integer('age');
        $table->timestamps();
    });
}

Run the migration:

php artisan migrate

1.4 Create a Controller for the API

Now, create a controller to manage the CRUD operations for users:

php artisan make:controller UserController

In app/Http/Controllers/UserController.php, add the CRUD methods:

<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    // Get all users
    public function index()
    {
        return response()->json(User::all());
    }

    // Create a new user
    public function store(Request $request)
    {
        $user = User::create($request->all());
        return response()->json($user, 201);
    }

    // Get a single user
    public function show($id)
    {
        return response()->json(User::find($id));
    }

    // Update user
    public function update(Request $request, $id)
    {
        $user = User::find($id);
        $user->update($request->all());
        return response()->json($user);
    }

    // Delete user
    public function destroy($id)
    {
        User::destroy($id);
        return response()->json(null, 204);
    }
}

1.5 Define API Routes

Next, open the routes/api.php file and define the routes for the UserController.

Route::get('users', [UserController::class, 'index']);
Route::get('users/{id}', [UserController::class, 'show']);
Route::post('users', [UserController::class, 'store']);
Route::put('users/{id}', [UserController::class, 'update']);
Route::delete('users/{id}', [UserController::class, 'destroy']);

1.6 Enable CORS

Since the frontend and backend will be hosted on different ports during development, we need to enable CORS (Cross-Origin Resource Sharing). You can install the Laravel CORS package:

composer require fruitcake/laravel-cors

Then, publish the configuration:

php artisan vendor:publish --provider="Fruitcake\Cors\CorsServiceProvider"

Configure config/cors.php to allow all origins during development:

'allowed_origins' => ['*'],
'allowed_methods' => ['*'],
'allowed_headers' => ['*'],

1.7 Test the API

You can test the API using Postman or Insomnia by sending HTTP requests to the following endpoints:

  • GET /api/users - Get all users.
  • POST /api/users - Create a new user.
  • GET /api/users/{id} - Get a specific user.
  • PUT /api/users/{id} - Update a user.
  • DELETE /api/users/{id} - Delete a user.

Step 2: Frontend - Angular

2.1 Install Angular

Create a new Angular project using the Angular CLI:

ng new angular-frontend
cd angular-frontend

2.2 Install HTTP Client Module

In your Angular project, you will use the HTTP client module to interact with the Laravel API. Import HttpClientModule in your app.module.ts:

import { HttpClientModule } from '@angular/common/http';

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

2.3 Create a User Service

Generate a service that will handle the API calls to the Laravel backend:

ng generate service user

In src/app/user.service.ts, add the following code to handle CRUD operations:

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

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private apiUrl = 'http://127.0.0.1:8000/api/users'; // Laravel API URL

  constructor(private http: HttpClient) {}

  getUsers(): Observable<any> {
    return this.http.get(this.apiUrl);
  }

  getUser(id: number): Observable<any> {
    return this.http.get(`${this.apiUrl}/${id}`);
  }

  createUser(user: any): Observable<any> {
    return this.http.post(this.apiUrl, user);
  }

  updateUser(id: number, user: any): Observable<any> {
    return this.http.put(`${this.apiUrl}/${id}`, user);
  }

  deleteUser(id: number): Observable<any> {
    return this.http.delete(`${this.apiUrl}/${id}`);
  }
}

2.4 Create a User Component

Generate a component to display and manage users:

ng generate component user

In src/app/user/user.component.ts, add logic to interact with the service:

import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
  users: any[] = [];
  user: any = { name: '', email: '', age: null };

  constructor(private userService: UserService) {}

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

  getUsers(): void {
    this.userService.getUsers().subscribe((data) => {
      this.users = data;
    });
  }

  createUser(): void {
    this.userService.createUser(this.user).subscribe(() => {
      this.getUsers();
      this.user = { name: '', email: '', age: null };
    });
  }

  updateUser(id: number): void {
    this.userService.updateUser(id, this.user).subscribe(() => {
      this.getUsers();
      this.user = { name: '', email: '', age: null };
    });
  }

  deleteUser(id: number): void {
    this.userService.deleteUser(id).subscribe(() => {
      this.getUsers();
    });
  }
}

2.5 Update the HTML Template

In src/app/user/user.component.html, create a simple form to add and update users:

<h2>User Management</h2>

<div>
  <input [(ngModel)]="user.name" placeholder="Name" />
  <input [(ngModel)]="user.email" placeholder="Email" />
  <input [(ngModel)]="user.age" type="number" placeholder="Age" />
  <button (click)="createUser()">Create User</button>
</div>

<ul>
  <li *ngFor="let u of users">
    {{ u.name }} ({{ u.email }}) - {{ u.age }}
    <button (click)="updateUser(u.id)">Update</button>
    <button (click)="deleteUser(u.id)">Delete</button>
  </li>
</ul>

2.6 Run the Angular Application

Run the Angular application:

ng serve

The Angular app will run on http://localhost:4200.

Step 3: Testing the Full Stack Application

  1. Run the Laravel server on http://127.0.0.1:8000 by running:
php artisan serve
  1. Access the Angular frontend at http://localhost:4200 to interact with the backend.

  2. You should be able to create, read, update, and delete users via the Angular frontend, which communicates with the Laravel backend.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete