Home Angular6 How to Save Angular 6 Form Data into Php Mysql with Laravel 5.7?

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

by therichpost
21 comments
Angular 9 Laravel 7 Auth Login working tutorial Part 2

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

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

 

Here are the some working example pictures:

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

 

mysql data laravel 5.7

 

In this post, I have used Bootstrap 4 for responsive layout, Angular 6 Reactive form module, Angular 6 HttpClient Module for sending and receiving data.  For add Bootstrap 4 into your Angular 6 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 6 data and save it into Php Mysql Database.

 

Here is the complete working and tested code:

 

First, I will go with Angular 6 code snippet:
1. First, add the below code into your app.module.ts file:

In this file, we declare the modules, which we use in our application.

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

 

2. Second, add below code into your Angular 6 app.component.ts file:

In this file, I have used Angular forms validators for validate the form, HttpClient for sending data, HttpParams for getting form data fields value.

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();
      })
    
      
    }
  
}

 

3. Third, add below code into your Angular 6 app.component.html file:

In this file, I have used some Bootstrap 4 elements and Angular 6 Reactive Form.

<div class="jumbotron text-center">
  <h1>Angular 6 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>

 

Now you are done with Angular 6 code, here comes with laravel 5.7 code snippet:

 

1. First, here is the code for your laravel 5.7 routes/api.php file:

In this file, we write the api’s, which deals with controller to get or post the data.

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

 

2. Second, here is the code for your Laravel 5.7 controller file:

 First you need to run below command to controller in laravel 5.7:

$ php artisan make:controller UserDetailsController
 
Second, now here the code for app\Http\Controllers\UserDetailsController.php file:

In this file, I wrote code to save the Angular 6 form data into Php mysql.

<?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 it is done and If you have any query related to this post then do ask questions of comment below.

 

 

You may also like

21 comments

mohammod December 2, 2018 - 2:59 pm

i m new in angular and larave can you plz explain thiese topic step by step

Reply
Ajay Malhotra December 2, 2018 - 3:02 pm

Hi Mohammod, did you install angular and laravel?

Reply
mohammod December 4, 2018 - 12:09 pm

yes sir i install angular6 and latest laravel

Reply
mohummod December 4, 2018 - 11:21 am

i try lot of example
in some example i am facing version isssue
sir i want post data to api
angular to laravel api
i working on the angulr6 and latest version on laravel

Reply
Ajay Malhotra December 4, 2018 - 3:01 pm

can you show me your code or you can email me your code and I will solve your problem.

Reply
shaikhmohammod December 6, 2018 - 11:04 am

sir the problem is short out

Reply
Ajay Malhotra December 6, 2018 - 3:30 pm

Great..

Reply
shaikhmohammod December 6, 2018 - 11:05 am

i am sending my data to my laravel api

Reply
shaikhmohammod December 6, 2018 - 11:06 am

thanks for giving me a response

Reply
Ajay Malhotra December 6, 2018 - 3:30 pm

Your welcome..

Reply
kartic maity January 25, 2019 - 6:36 am

my error is given bellow:
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: “Unknown Error”, url: null, ok: false, …}

Reply
Ajay Malhotra January 27, 2019 - 6:23 am

can you please show the code?

Reply
ammar December 13, 2018 - 10:50 am

im getting POST 404 (Not Found)

Reply
Ajay Malhotra December 13, 2018 - 5:06 pm

There must be something wrong in your laravel code..

Reply
Denial December 13, 2018 - 11:24 am

Thank you for this post 🙂

Reply
Ajay Malhotra December 13, 2018 - 5:05 pm

Your welcome denial

Reply
kartic maity January 25, 2019 - 4:22 am

hello sir i can use
var fd:FormData=new FormData(); //instead of let Params = new HttpParams();

fd.append(’email’,’fgmail.com’);

this.http.post(‘nglv/api/form’,fd).subscribe((data)=>{

})
}
is this code work or not?

Reply
Ajay Malhotra January 27, 2019 - 7:02 am

Hi Kartic, yes you can try this.

Reply
kartic maity January 25, 2019 - 4:23 am

hi

Reply
linga January 25, 2019 - 6:27 am

ccess to XMLHttpRequest at ‘http://localhost:8000/adduserdetails’ from origin ‘http://localhost:4200’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Reply

Leave a Comment

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