AppDividend
Latest Web Development Tutorials

Laravel 5.5 Angular 4 Tutorial Example From Scratch

Laravel AngularJS Tutorial

8,229

Laravel 5.5 Angular 4 Tutorial Example From Scratch is today’s topic. Laravel is PHP Web Application Framework. Angular 4 or just Angular is Popular Front End Framework for creating a client-side application. Today we will see how we can use both and how we can interact with each other via an API. We simply build one interface in Angular 4 Application and then call an API to store the data. This is just a basic Item Storage Application using Angular 4 and Laravel 5.5. This example is a showcase of how we can use both to create a full stack application and how we can connect with an API.

Laravel 5.5 Angular 4 Tutorial

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

Step 1: Setup an Angular 4 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 install, type the following command.

cd ng4tutorial
ng serve --open

Step 2: Create one form to enter the data.

Angular 4 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 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>Ng4app</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.

For creating the form, we need to modify the app.component.html file. This file resides in 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.

Laravel AngularJS Tutorial

 

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

Related Posts
1 of 3
<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.

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

First, we need to import two modules in 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 have used Promise and Observables. 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

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

Start the Laravel Development server by the typing the following command.

php artisan serve

Step 6: Resolve 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 config/app.php 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"

Now, try again, it will save the data into the database. I have not set the redirect after saving the data but will set in short, while you can check the values in the database.

For now, this is enough, we can build CRUD functionality in the next article. So stay tuned.

This is the basic example of Laravel 5.5 Angular 4 Tutorial.

 

16 Comments
  1. LordApo says

    Why don’t you use Lumen? It’s made for this purpose and way faster than Laravel.

  2. […] 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 😛

  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.

  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.

  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.

Leave A Reply

Your email address will not be published.