Laravel and Angular: Creating a Full-Stack CRUD Application
Step 1: Backend - Laravel
1.1 Install Laravel
First, create a new Laravel project using Composer.
After installing, navigate to the project directory:
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.
Run the migration to set up the default tables (optional, for user authentication):
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.
Update the migration file (database/migrations/xxxx_xx_xx_create_users_table.php
) to define the schema:
Run the migration:
1.4 Create a Controller for the API
Now, create a controller to manage the CRUD operations for users:
In app/Http/Controllers/UserController.php
, add the CRUD methods:
1.5 Define API Routes
Next, open the routes/api.php
file and define the routes for the UserController.
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:
Then, publish the configuration:
Configure config/cors.php
to allow all origins during development:
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:
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
:
2.3 Create a User Service
Generate a service that will handle the API calls to the Laravel backend:
In src/app/user.service.ts
, add the following code to handle CRUD operations:
2.4 Create a User Component
Generate a component to display and manage users:
In src/app/user/user.component.ts
, add logic to interact with the service:
2.5 Update the HTML Template
In src/app/user/user.component.html
, create a simple form to add and update users:
2.6 Run the Angular Application
Run the Angular application:
The Angular app will run on http://localhost:4200
.
Step 3: Testing the Full Stack Application
- Run the Laravel server on
http://127.0.0.1:8000
by running:
Access the Angular frontend at
http://localhost:4200
to interact with the backend.You should be able to create, read, update, and delete users via the Angular frontend, which communicates with the Laravel backend.