How to integrate Angular with Laravel

Updated: January 18, 2024 By: Guest Contributor Post a comment

Introduction

Integrating Angular with Laravel is a popular choice for developers looking to leverage the structural framework of Angular with the back-end capabilities of Laravel. Angular is a client-side TypeScript-based framework, while Laravel is a server-side PHP framework. Combining these two can lead to powerful web applications. This tutorial will walk you through the process of integration step-by-step.

Prerequisites

  • Basic knowledge of Angular
  • Basic knowledge of Laravel
  • Node.js and npm installed
  • Composer for managing PHP dependencies

Setting Up Laravel

composer create-project --prefer-dist laravel/laravel LaravelAngularProject

This command creates a new Laravel project named LaravelAngularProject. Next, move into your project directory:

cd LaravelAngularProject

Setting Up Angular

Once inside your Laravel project directory, you can now install Angular:

ng new client

This creates an Angular application in a new ‘client’ directory within your Laravel project.

Create RESTful API with Laravel

Laravel is exceptionally well-suited for developing APIs. Routes for an API can be defined within the ‘routes/api.php’ file:

use Illuminate\Http\Request;

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

// Sample route
Route::get('/items', 'ItemController@index');

Create a new controller:

php artisan make:controller ItemController

Add functionality to ‘ItemController’:

<?php

namespace App\Http\Controllers;

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

class ItemController extends Controller
{
    public function index()
    {
        $items = Item::all();
        return response()->json($items);
    }
}

Connect Angular to Laravel API

Switch to the Angular application directory:

cd client

Create a service for interacting with the Laravel API:

ng generate service data

Add methods in ‘data.service.ts’ to get data:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class DataService {

  private baseUrl = 'http://localhost:8000/api';

  constructor(private http: HttpClient) { }

  getAllItems(): Observable<any> {
    return this.http.get(`${this.baseUrl}/items`);
  }
}

In your Angular component, inject this service and use it to fetch items:

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
  selector: 'app-item-list',
  templateUrl: './item-list.component.html',
  styleUrls: ['./item-list.component.css']
})
export class ItemListComponent implements OnInit {

  items: any = [];

  constructor(private dataService: DataService) { }

  ngOnInit(): void {
    this.dataService.getAllItems().subscribe(data => {
      this.items = data;
    });
  }
}

Serve the Angular Application

To enable the Angular application, run the Angular development server:

ng serve

The Angular application will be served at ‘localhost:4200’, ensuring it communicates effectively with the Laravel API, which by default runs at ‘localhost:8000’.

Handling CORS

Cross-Origin Resource Sharing (CORS) can restrict the Angular application from accessing resources from Laravel. To overcome this, adjust Laravel’s middleware:

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    public function handle($request, Closure $next)
    {
        return $next($request)
          ->header('Access-Control-Allow-Origin', '*')
          ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
          ->header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin, Authorization');
    }
}

Register your Cors middleware in ‘app/Http/Kernel.php’:

protected $middleware = [
    // ...
    App\Http\Middleware\Cors::class,
];

By integrating Angular with Laravel, you now have the ability to create responsive and powerful web applications using a modern JavaScript framework and a robust PHP back end. With further customization, you can harness the full set of features offered by both Angular and Laravel.

Conclusion

Through this guide, we covered the steps necessary to connect an Angular front end with a Laravel back end. With practice and further exploration into both frameworks, you can build scalable and maintainable web applications that cater to modern web development needs.