Angular7LaravelLaravl 5.7

How to Save Angular 7 Form Data into Php Mysql with Laravel 5.7?

Angular 8 Grouped Bar chart using data Laravel 6 REST api

Save Angular 7 Form Data into Php Mysql with Laravel 5.7

Views

Hello to all, welcome to therichpost.com. In this post, I will tell you, How to Save Angular 7 Form Data into Php Mysql with Laravel 5.7?

Angular 7 and Laravel 5.7 both are launched recently. Both came with new features. Today we will save Angular 7 form data into Php MySQL database with the help of Laravel 5.7. 

 

Here are the some working example pictures:

 

 

Save Angular 7 Form Data into Php Mysql with Laravel 5.7

 

In this post, I have used Bootstrap 4 for responsive layout, Angular 7 Reactive form module, Angular 7 HttpClient Module for sending and receiving data.  For add Bootstrap 4 into your Angular 7 app, you can get this from :

 https://therichpost.com/add-bootstrap-4-to-angular-6

For backend, I have used laravel 5.7 Api’s for get Angular 7 data and save it into Php Mysql Database.

 

Here is the working and tested code you need to follow:

 

1. Very first, you need to run common below commands to add Angular 7 project on your machine:

$ npm install -g @angular/cli 

$ ng new angulardatasavelaravel //Install Angular Project

$ cd angulardatasavelaravel // Go to project folder

$ ng serve //Run Project

http://localhost:4200/ //Run On local server

2. Now you need to add the below code into your app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
  BrowserAnimationsModule,
  ReactiveFormsModule,
  HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

3. Now you need to add below code into your Angular 7 app.component.ts file: 

import {Component} from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpClient, HttpParams } from '@angular/common/http';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  registerForm: FormGroup;
  submitted = false;

    constructor(private formBuilder: FormBuilder, private http: HttpClient) { }

    ngOnInit() {
        this.registerForm = this.formBuilder.group({
            firstName: ['', Validators.required],
            email: ['', [Validators.required, Validators.email]],
        });
    }

    // convenience getter for easy access to form fields
    get f() { return this.registerForm.controls; }
    onSubmit() {
        this.submitted = true;

        // stop here if form is invalid
        if (this.registerForm.invalid) {
            return;
        }
    // Initialize Params Object
    let Params = new HttpParams();

    // Begin assigning parameters
    Params = Params.append('firstParameter', this.registerForm.value.firstName);
    Params = Params.append('secondParameter', this.registerForm.value.email);
    return this.http.post('http://localhost/laravel57/public/api/adduserdetails'
    ,{
    params: { params: Params }
    }).subscribe((res: Response) => {
        alert(res);
    //this.registerForm.reset();
      })
    
      
    }
  
}

4. Now you need to add into your Angular 7 app.component.html file:

<div class="jumbotron text-center">
  <h1>Angular 7 Save Form Data into PhpMysql with Laravel 5.7
</h1>
</div>
    <div class="container">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
                    <div class="form-group">
                        <label>First Name</label>
                        <input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }" />
                        <div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
                            <div *ngIf="f.firstName.errors.required">First Name is required</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
                        <div *ngIf="submitted && f.email.errors" class="invalid-feedback">
                            <div *ngIf="f.email.errors.required">Email is required</div>
                            <div *ngIf="f.email.errors.email">Email must be a valid email address</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <button class="btn btn-primary">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

5. Laravel Code Start:

 

6. Here is the code for your laravel 5.7 routes/api.php file:

Route::post("/adduserdetails", "UserDetailsController@userDetails");

7. H ere is the command you need to run to make new laravel contoller file:

$ php artisan make:controller UserDetailsController

8. Now you need to all below  code into app\Http\Controllers\UserDetailsController.php file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class UserDetailsController extends Controller
{
    public function userDetails(Request $req)
  {
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: PUT, GET, POST");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
    foreach($req->params as $postdata)
    {
      $datainserted = DB::table('userdata')->insert(
      ['name' => $postdata['updates'][0]['value'], 'email' => $postdata['updates'][1]['value']]
        );
      if($datainserted)
      {
        return response()->json("Data Added Successfully");
      }
    }
    
  }
}

Now run your Angular project and save your angular data into laravel database and don’t forget to add your database details into laravel .env file.

if you have any query related to this post, then do comment below or ask question.

Thank you,

Jassa Put,

TheRichPost

 

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am full stack developer. I love coding. I know Wordpress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, laravel, Codeigniter, Shopify, Squarespace, Jquery, Google Map Api, Vuejs, Reactjs, Bigcommerce etc.

1 Comment

Leave a Reply

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

Positive SSL