Laravel 5.3 with Angular 2 - Setup

Published 1 year ago by eliyas5044

Hello,

Finally i found a way to setup laravel 5.3 with angular 2. I will try to tell how i do that...

  1. First with new laravel 5.3 setup, there is a package.json file. Paste this code in this file.
{
  "name": "YourProjectName",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "prod": "gulp --production",
    "dev": "gulp watch",
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "@angular/upgrade": "2.0.0",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.27",
    "zone.js": "^0.6.23",
    "angular2-in-memory-web-api": "0.0.20",
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "bootstrap-sass": "^3.3.7",
    "gulp": "^3.9.1",
    "jquery": "^3.1.0",
    "laravel-elixir": "^6.0.0-9",
    "laravel-elixir-vue": "^0.1.4",
    "laravel-elixir-webpack-official": "^1.0.2",
    "lodash": "^4.14.0",
    "vue": "^1.0.26",
    "vue-resource": "^0.9.3",
    "elixir-typescript": "2.0.0",

    "concurrently": "^2.2.0",
    "lite-server": "^2.2.2",
    "typescript": "^2.0.2",
    "typings":"^1.3.2"
  }
}
  1. Create a file- tsconfig.json in your root directory.
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}
  1. Create a file- typings.json in your root directory.
{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  }
}
  1. Write command in your terminal-
npm install
  1. After install go- node_modules> elixer-typescript> index.js file and comment this line as shown in code
 //.pipe($.concat(paths.output.name))     
  1. Create a folder in resources>assets>typescript and create three file- app.component.ts, app.module.ts, main.ts

app.module.ts

///<reference path="../../../typings/index.d.ts"/>

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: '<h1>My First Angular App</h1>'
})
export class AppComponent { }

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);
  1. Open gulpfile.js and paste this code...
const elixir = require('laravel-elixir');

require('laravel-elixir-vue');
require('elixir-typescript');


/*
 |--------------------------------------------------------------------------
 | Elixir Asset Management
 |--------------------------------------------------------------------------
 |
 | Elixir provides a clean, fluent API for defining some basic Gulp tasks
 | for your Laravel application. By default, we are compiling the Sass
 | file for our application, as well as publishing vendor resources.
 |
 */

elixir(mix => {
    mix.sass('app.scss')
    .webpack('app.js')
    .copy('node_modules/@angular', 'public/@angular')
    .copy('node_modules/anular2-in-memory-web-api', 'public/anular2-in-memory-web-api')
    .copy('node_modules/core-js', 'public/core-js')
    .copy('node_modules/reflect-metadata', 'public/reflect-metadata')
    .copy('node_modules/systemjs', 'public/systemjs')
    .copy('node_modules/rxjs', 'public/rxjs')
    .copy('node_modules/zone.js', 'public/zone.js')

    .typescript(
        [
            'app.component.ts',
            'app.module.ts',
            'main.ts'
        ],
        'public/app',
        {
            "target": "es5",
            "module": "system",
            "moduleResolution": "node",
            "sourceMap": true,
            "emitDecoratorMetadata": true,
            "experimentalDecorators": true,
            "removeComments": false,
            "noImplicitAny": false
        }
    );
})
;

  1. Make a directory in public>app and write command in your terminal-
gulp
  1. Create a file systemjs.config.js in your public directory.
/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
    System.config({

        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',
            // angular bundles
            '@angular/core': '@angular/core/bundles/core.umd.js',
            '@angular/common': '@angular/common/bundles/common.umd.js',
            '@angular/compiler': '@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': '@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': '@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': '@angular/http/bundles/http.umd.js',
            '@angular/router': '@angular/router/bundles/router.umd.js',
            '@angular/forms': '@angular/forms/bundles/forms.umd.js',
            // other libraries
            'rxjs':                       'rxjs',
            'angular2-in-memory-web-api': 'angular2-in-memory-web-api',
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            },
            'angular2-in-memory-web-api': {
                main: './index.js',
                defaultExtension: 'js'
            }
        }
    });
})(this);

  1. After that in your welcome.blade.php paste this code
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel 5.3 - Angular 2</title>

        <!-- 1. Load libraries -->
        <!-- Polyfill(s) for older browsers -->
        {{ Html::script('core-js/client/shim.min.js') }}
        {{ Html::script('zone.js/dist/zone.js') }}
        {{ Html::script('reflect-metadata/Reflect.js') }}
        {{ Html::script('systemjs/dist/system.src.js') }}
        {{ Html::script('systemjs.config.js') }}

        <script>
            System.import('app').catch(function(err){ console.error(err); });
        </script>
    </head>
    <!-- 3. Display the application -->
    <body>
    <my-app>Loading...</my-app>
    </body>
</html>

Congrats! You are ready to open your first Angular 2 with Laravel 5.3 app in your browser. So open it !

Best Answer (As Selected By eliyas5044)
eliyas5044

Hey, I was wrong. It is a best practice to make angular and laravel completely separate file. So i made two repository in github to make easy for everyone. Checkout now !

The link of these two repository -

angular

laravel

Where angular as a front-end and laravel as a back-end.

eliyas5044

@manshu - sorry, i forgot to tell about this line, paste it in your app.module.ts file at top, see code in above now-

///<reference path="../../../typings/index.d.ts"/>

For missing this line, elixer-typescript not working.

manshu
manshu
1 year ago (78,945 XP)

You can clone the code from

https://github.com/manshu/laravel-angular2

eliyas5044

@manshu - Here the repository in github. You can check it. https://github.com/eliyas5044/laravel5.3-angular2

primordial

@eliyas5044 I use Angular2 and can I suggest you should not be using Angular/2 in the same domain as Laravel. I have several Restful Laravel/Lumen APIs each inside their own domain. My Angular/2 frontend cares not what PHP framework I am using.

Build a Laravel API then use the Angular/2 quickstart tutorial to try and talk to your API from a completely separate domain. I sincerely believe you have taken a wrong turn.

eliyas5044

@primordial - I am new in angular 2 and have some knowledge about laravel. I was searching, how can i use laravel as backend and angular 2 as frontend. So if you can help me that will be great :)

primordial

@eliyas5044 One of the major advantages of a solution such as Angular is the ability to decouple the frontend from the backend. As such, you don't want both inside the same codebase, defeats the object. Neither should know/care about the other.

Start by building a Restful API in Laravel or Lumen. There are plenty of tutorials out there. You merely need one controller with basic CRUD functionality that will respond with JSON encoded data.

Once you have mastered the API start with the Angular.io quickstart/hero tutorial inside a totally different domain. Once you have finished the tutorial you will have a much better idea of the architecture and should know how to get your angular frontend talking to your laravel backend. Feel free to ask any specific questions.

eliyas5044

@primordial - Imagine, i got a job from client to build a website. He will give me one domain to host all data. So how can i use two domain to host laravel and angular? If i use laravel and angular same domain, is there any problem? Please let me know briefly.

Ruffles
Ruffles
1 year ago (282,670 XP)

There's no problem, but I believe that front end frameworks should be independent from the back end and they shouldn't care what language serves them data. Also, if front end developers take over the angular 2 part, they shouldn't really know Laravel at all.

primordial

@eliyas5044 I would create a subdomain

mydomain.com - Angular frontend

api.mydomain.com - Laravel API

kreitje
kreitje
1 year ago (35,495 XP)

If i use laravel and angular same domain, is there any problem? Please let me know briefly.

One thing I have ran into in the past is your 404 page will need need to catch and render the angular app.

So if you have a /user/john-doe route in angular, and you refresh the page in the browser, you would want to defer that to your angular frontend and pull from the right endpoints instead of running through Laravel.

If you must keep everything on the same domain, I would put all your ajax calls into it's own prefixed routes like /api, /api/user/john-doe to make sure they don't collide with any on the angular side.

primordial

@eliyas5044 If you absolutely have to combine both code bases I would suggest not using Angular/2 on this project, wait for another opportunity. It is not designed for what you have in mind. Use jQuery or similar for this project, it is a better solution for the circumstances. Maybe Vue.js would be suitable? It is the recommended javascript framework for Laravel. Unfortunately I have no experience of Vue.js.

baconCheeseFry

I run an Angular and Laravel on the same domain and it works great. Of course it is designed for this: It is a frontend framework. As was mentioned, keep all your api calls with a 'api/v1' (or similar) prefix. Anything else gets routed to resources/views/index.php which is actually the Angular2 entry point. I have my angular codebase in a ng2 folder within the Laravel folder structure. My build process compiles the Angular files into the public folder and puts the index.html that the Angular build process creates into the resources/views folder as index.php and the paths within the index.php are set relative to the public folder. The build processes for Laravel and Angular are kept separate. My deployment script runs the composer install related commands and then moves into the ng2 folder and runs the Angular build process. I use the angular2-seed as my base with the modifications needed to put the files where they need to be.

primordial

@baconCheeseFry I honestly cannot imagine a scenario where combining the codebase is a good idea. It is a decoupled solution and should be implemented as such. However, it appears to be a very common Vue approach. Each to their own I suppose.

eliyas5044

@primordial - May i get a angular2 code with laravel5.3? I am stucked to connect angular 2 with laravel api. If possible, please create a github repo.

Lansana

I love the idea of isolation of backend and frontend

Please sign in or create an account to participate in this conversation.