AppDividend
Latest Code Tutorials

Laravel Angular: How to Use Angular with Laravel Example

Laravel Angular Tutorial

Laravel is a PHP Web Application Framework. Angular is the Popular Front End Framework for creating a client-side application. Today we will see how we can use both and interact with each other via an API.

We build one interface in Angular Application and then call an API to store the data. This is just a basic Item Storage Application using Angular and Laravel. This example shows how we can use both to create a full-stack application and how we can connect with an API.

Overview of Laravel Angular Project

• Step 1: Setup Angular project.
• Step 2: Create a form using Angular forms.
• Step 3: Handle the input data coming from the form using Angular.
• Step 4: Send the form data to the Laravel server.
• Step 5: Create Laravel backend: create table, views, controllers, models.
• Step 6: Resolve the cors problem. You can be finally able to save the data to the database.

Laravel Angular Example Tutorial

First, we are going to set up an Angular project at the client-side. For that, you can use angular-cli for boilerplate for our application. You can find this on the Angular website Link: Set up the Development Environment.

Step 1: Setup an Angular Environment.

First, we need to install Angular CLI globally. So type the following command.

npm install -g @angular/cli

Okay, now we need to create one project; let us call it ng4tutorial.

Type the following command in your terminal.

ng new ng4tutorial

It will create some files and folders and also install all the front end dependencies.

After installation, type the following command.

cd ng4tutorial
ng serve --open

Step 2: Create one form to enter the data.

Angular is totally modular. All the component files reside in the src  >>  app folder.

We are using Bootstrap CSS Framework to design our form. So I have downloaded the bootstrap CSS file in src  >>  assets directory called app.css file.

Our index.html file looks like this.

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Ng4app</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<body>
<app-root></app-root>
</body>
</html>

All the public static files are served from the assets folder.

For creating the form, we need to modify the app.component.html file. This file resides in the src  >>  app directory.

<!--The whole content below can be removed with the new code.-->
<div class="container">
<h1>
Welcome to {{title}}!!
</h1>
<hr />
<form>
<div class="form-group">
<label for="name">Item Name:</label>
<input type="text" class="form-control">
</div>
<div class="form-group">
<label for="price">Item Price:</label>
<input type="text" class="form-control">
</div>
</form>
</div>

Our app.component.ts file looks like this.

// app.component.ts

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Laravel Angular 4 App';
}

Our Form looks like this.

Step 3: Handle the input data.

First of all, we need to import two modules in the app.module.ts file.

1. FormsModule
2. HttpModule

And these modules are also included in the import array. So our src  >>  app  >>  app.module.ts file looks like this.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule }   from '@angular/forms';
import { HttpModule }    from '@angular/http';

import { AppComponent } from './app.component';

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

Now, we need to include Angular Form Object into our HTML. Our final code of app.component.ts looks like this.

// app.component.ts

<div class="container">
<h1>
Welcome to {{title}}!!
</h1>
<hr />
<form (ngSubmit)="onSubmit(fm)" #fm="ngForm">
<div class="form-group">
<label for="name">Item Name:</label>
<input type="text" class="form-control" ngModel name="name">
</div>
<div class="form-group">
<label for="price">Item Price:</label>
<input type="text" class="form-control" ngModel name="price">
</div>
</form>
</div>

We have added one attribute to the input box called “ngModel“. This attribute tells angular that how many values are there in the HTML Form. It creates an object, and later, after submits, we can access that object and pull out the values from it.

<form (ngSubmit)="onSubmit(fm)" #fm="ngForm">

It is the way to tell AngularJS that it needs to create an object that describes the whole form element and its values.

After press, the submit, onSubmit() function is called, and in that, we can get all the values of the form.

// app.component.ts

import { Component } from '@angular/core';
import { Item } from './Item';
import { NgForm }   from '@angular/forms';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Laravel Angular 4 App';
onSubmit(form: NgForm){
console.log(form.value);
}
}

Here onSubmit() function, we get all the form values. Now, we can send the POST request to the Laravel Server.

Step 4: Send the data to the Laravel server.

The next step would be to call the HTTP Service to handle the POST request.

First, we need to import two modules in the app.component.ts file.

import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/toPromise';

The further step would be to call that service. This is my full code of the app.component.ts file.

// app.component.ts

import { Component, Injectable } from '@angular/core';
import { Item } from './Item';
import { NgForm }   from '@angular/forms';
import { Http, Headers } from '@angular/http';

@Injectable()
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _http: Http){}
title = 'Laravel Angular 4 App';
onSubmit(form: NgForm): Promise <Item>{
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}


I have used Promise and Observables. I also imported it on the Top.

Step 5: Create A Laravel Backend For the Request.

Create one Laravel project by typing the following command.

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

Edit the .env file to set the MySQL database credentials.

Next, switch to your command-line interface and type the following command.

php artisan make:model Item -m

Please navigate to the migration file in the database  >>  migrations  >>  create_items_table and copy the following code into it.

<?php

// create_items_table

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateItemsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('items', function (Blueprint $table) {$table->increments('id');
$table->string('name');$table->integer('price');
$table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('items'); } } Type the following command in your terminal. php artisan migrate Create one controller called ItemController. php artisan make:controller ItemController Register the routes in the routes >> api.php file. Route::post('items', 'ItemController@store'); In the Item.php model, we need to include the$fillable property to prevent the mass assignment exceptions.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
protected $fillable = ['name', 'price']; }  Write the store function in the ItemController.php file to save the data into the database. <?php // ItemController.php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Item; class ItemController extends Controller { /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request$request
* @return \Illuminate\Http\Response
*/
public function store(Request $request) {$item = new Item([
'name' => $request->get('name'), 'price' =>$request->get('price')
]);

protected $middleware = [ // ... \Barryvdh\Cors\HandleCors::class, ]; You can publish the config using this command: php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider" Now, try again; it will save the data into the database. I have not set the redirect after saving the data but will set it short while you can check the values in the database. This is the basic example of Laravel Angular Example Tutorial. Recommended Posts Laravel CRUD Angular CRUD Angular Forms Angular HTTPClient Laravel Form Validation 44 Comments 1. LordApo says Why don’t you use Lumen? It’s made for this purpose and way faster than Laravel. 2. Laravel 5.5 Angular 4 Tutorial Example From Scratch – Angular Questions […] submitted by /u/KrunalLathiya [link] […] 3. Leandrit Ferizi says Thanks for this, however could you make a tutorial on how to pass an image stored in Laravel Storage through api to the angular 4 and the image to show up? I know through Vue but Laravel and Angular are two separate projects 😛 1. Sharat says 4. Sinan says hi, i get these error upto Step: 4 ERROR in [APP_PATH]/src/app/app.component.ts (2,22): Cannot find module ‘./Item’. ERROR in [APP_PATH]/src/app/app.component.ts (17,110): Property ‘headers’ does not exist on type ‘AppComponent’. Dunno What is wrong i just got it exactly as it is on the tutorial 1. Krunal says import { Http, Headers } from ‘@angular/http’; private headers = new Headers({‘Content-Type’: ‘application/json’}); It will resolve that issue. 1. Sinan says i have tried that, but doesn’t work. do u have this on github; i have updated import { Http } from ‘@angular/http’; to import { Http, Headers } from ‘@angular/http’; and added private headers = new Headers({‘Content-Type’: ‘application/json’}); inside like; export class AppComponent { …. …. private headers = new Headers({‘Content-Type’: ‘application/json’}); } 2. Takis Koumoutsakos says Actually I created a file named item.ts with the following code: export interface Item { name: string; price: number; } and then added the code: import {Item} from ‘./item’; to app.component.ts This is the same as Krunal’s code except for the lower case “i” in the import. 5. ankit says Hi Krunal . It’s nice way to explain. i get same Cannot find module ‘./Item’ at app.component.ts. Can you please help to short it out. 1. Farhan Ali says did you find the solution of that or still not? i am facing the same problem. 1. savi says 1.import { Item } from ‘http://localhost/testlaravel/Item’; replace this line of code in app.component.ts 2.add use App\item in itemcontroller.php data will get inserted 2. savi says also change the path of http to http://localhost/project_name/api/items 6. Pratik says Hello Krunal, Its good tutorial to have but i’m facing one issue where i don’t get anything in request object in store method can you help me out on this 7. Soundar Rajan says I am not able to execute this command ng new ng4tutorial. i get the error ‘ng’ is not recognized as an internal and external command 1. Krunal says Please install angular cli globally in your pc in the administrator mode. 2. John Maina says Hi @Soundar please visit https://yarnpkg.com/lang/en/docs/install/ and download yarn the install, it will solve the problem 8. Soundar Rajan says Thanks Krunal for the immediate response. I did install so many times in C: and/or C://Projects but still the same issue. Please help me to 9. Robin says Do I need two different servers (Artisan for Laravel and npm for Angular) to run for this? Or can I package both the applications in on server? Thanks Robin 10. Rakib says Hello Krunal, On angular response I am always getting “Header Not Allowed” !! why this is happening?? 11. sreenidhi says hii, I am getting No ‘Access-Control-Allow-Origin’ header is present on the requested resource 1. Krunal says use laravel-cors module. 12. sreenidhi says hello Kurnal, Iam getting error: Uncaught (in promise): Response with status: 0 for URL: null at resolvePromise 13. Arsani Boshra says Still have problem with CORS .. Trying to test my local api with angular and I still get 404. Thanks 14. Nithya says hi Is article available for crud functionality 15. sri says hi kurnal Can you make tutorial on CRUD functionality 16. Vishwas Jadav says Wonderful Work 17. Vishwas Jadav says Please complete the article for CRUD I want to learn from it. 18. Amr Ahmed says How can i make route (‘/’) show index.html instead of welcome.blade.php? thanks in advance. 19. Jose says Fantastic tutorial 20. Farhan Ali says I am facing problem that error TS2307: cannot find module ‘/Item’ 21. vignesh says please give CRUD functionality with angular4 and laravel 22. Jr Klaus MOMBO-NZAHOU says Thank you very much! 23. Marthell says Hi, the CRUD functionality will post in this article? if exist, where is? 24. shakyl says when will you post the article for crud using laravel and angular?? 25. Pratik says Hi,I am not able to store data in database.Can you help me out?My code is running without any error but it is unable to store data in database. Thanks 1. Krunal says can you double check your post request please? 26. Evgeny says Hello, please tell me how to display values from the database? 1. Hassan Ali says hello evgeny plzz if u found your search to get values back from database and displayed back again in the angular view any tutorials plz thans 27. Sam says Nice tutorial, but you call Angular 4 as AngularJS. Angular and AngularJS are not the same… 28. vikas says Sir you are amazing. i cant’t say anything because i’m learn everything from your tutorials. God bless you sir . 29. Loganathan says Thanks Buddy, you made it easy. 30. Aashu Singh says This helped me a lot , but im getting an issue when im trying to retrive data from teh api by using$request->input() . When im using $request->input() im getting null value , if anyone help me with this 31. Ghizlane KHATTARI says i get this msg error when i run the command “$ composer require barryvdh/laravel-cors ”
Warning: Ambiguous class resolution, “Fruitcake\Cors\CorsServiceProvider” was found 2x: in “C:/xampp/htdocs/ng4Laravel55/vendor/barryvdh/laravel-cors/src/CorsServiceProvider.php” and “C:/xampp/htdocs/ng4Laravel55/vendor/fruitcake/laravel-cors/src\CorsServiceProvider.php”, the first will be used.
Warning: Ambiguous class resolution, “Fruitcake\Cors\HandleCors” was found 2x: in “C:/xampp/htdocs/ng4Laravel55/vendor/barryvdh/laravel-cors/src/HandleCors.php” and “C:/xampp/htdocs/ng4Laravel55/vendor/fruitcake/laravel-cors/src\HandleCors.php”, the first will be used.