How to Setup Laravel With Angular [Complete Step-by-Step Guide]

Here is the step-by-step guide to setting up Laravel with Angular.

Step 1: Set up an Angular Environment.

Install Angular CLI globally. So type the following command.

npm install -g @angular/cli

Type the following command to create a project.

ng new ngtutorial

Step 2: Create one form to enter the data.

Angular is 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">
<head>
  <meta charset="utf-8">
  <title>Ngapp</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="/assets/app.css" rel="stylesheet">
</head>
<body>
  <app-root></app-root>
</body>
</html>

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

To create 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>
      <button type="submit" class="btn btn-primary">Add</button>
    </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.

Angular create form

Step 3: Handle the input data.

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 { }

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>
      <button type="submit" class="btn btn-primary">Add</button>
    </form>
</div>

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

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

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

After pressing, the submit, the 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';
import 'rxjs/add/operator/toPromise';

@Injectable()
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
	constructor(private _http: Http){}
        private headers = new Headers({'Content-Type': 'application/json'});
  	title = 'Laravel Angular 4 App';
  	onSubmit(form: NgForm): Promise <Item>{
        return this._http.post('http://127.0.0.1:8000/api/items', JSON.stringify(form.value), {headers: this.headers})
  		   .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 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 ngLaravel

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

Switch to your command-line interface and type the following command.

php artisan make:model Item -m

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

<?php

// create_items_table

use Illuminate\Support\Facades\Schema;
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 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')
        ]);
        $item->save();
        return response()->json('Successfully added');
    }
}

Start the Laravel Development server by typing the following command.

php artisan serve

Step 6: Resolve the CORS problem

Download the following Laravel Specific CORS package to avoid this issue and follow the steps.

composer require barryvdh/laravel-cors

Add the Cors\ServiceProvider to your provider’s array.

Barryvdh\Cors\ServiceProvider::class,

To allow CORS for all your routes, add the HandleCors middleware in the $middleware property of app/Http/Kernel.phpclass:

protected $middleware = [
    // ...
    \Barryvdh\Cors\HandleCors::class,
];

You can publish the config using this command:

php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

Try again; it will save the data into the database. After saving the data, I have not set the redirect but will set it short while you check the database values.

That’s it!

44 thoughts on “How to Setup Laravel With Angular [Complete Step-by-Step Guide]”

  1. Pingback: Laravel 5.5 Angular 4 Tutorial Example From Scratch – Angular Questions
  2. 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 😛

    Reply
  3. 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

    Reply
      • 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’});
        }

        Reply
    • 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.

      Reply
  4. 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.

    Reply
  5. 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

    Reply
  6. 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

    Reply
  7. 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

    Reply
  8. 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

    Reply
  9. 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

    Reply
    • 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

      Reply
  10. 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

    Reply
  11. 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.

    please i need help

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.