ionic 3 crud with laravel backend


I. Server-side

step 1 : create new laravel app

// using composer

composer create-project --prefer-dist laravel/laravel yourproject

// using Laravel Installer

laravel new yourproject

step 2 : create migrate table after you filled information at .env file

php artisan make:migration create_table_yourtablename

now let set up your table

// project/database/migrations/YYYY_MM_DD_XXXXXX_create_table_tbitem.php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTableTbitem extends Migration
{
    
    public function up()
    {
        //
        Schema::create('tbitems', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    
    public function down()
    {
        //
        Schema::dropIfExists('tbitems');
    }
}

then run command to create your table in database and create model

// migrate table to database
php artisan migrate

// create table model
php artisan make:model tbitems

step 3 : go to your route/api.php then write code like below . they are route for crud exactly.

// route/api.php

use App\tbitem;

Route::get('/data',function(){
	
	$items = tbitem::all()->toJson();
	return response($items,200)->header('Content-Type', 'application/json');

});

Route::post('/data/create',function(Request $req){
	
    //data request from client side should be looked like this
	//{"name":"a"}
	//[{"name":"b"},{"name":"c"}]

	$data = $req->json()->all();

	$item = new tbitem();

	$item->name = $data['name'];

	$item->save();

	return response(($result === true ? 'succeed':'failed'),200)->header('Content-Type', 'application/json');

});


Route::put('/data/update',function(Request $req){
	
    $data = $req->json()->all();

	$item = tbitem::find($data['id']);

	$item->name = $data['name'];

    $item->save();

	return response(($result === true ? 'succeed':'failed'),200)->header('Content-Type', 'application/json');

});


Route::delete('/data/delete',function(Request $req){
	
    $data = $req->json()->all();

	$result = tbitem::destroy($data['id']);

	return response(($result === true ? 'succeed':'failed'),200)->header('Content-Type', 'application/json');

});

*** then you can test your server with rest tool to make sure nothing wrong. ok let go check our client side.

II. Client-side

step 1 : create new ionic application

ionic start your-application --v2

just so you know , ionic currently is updating to version 3 that why code work here can be run old someday . for more detail about ionic go http://ionicframework.com/docs/.

step 2 : create provider in your project

server.ts

import { Injectable } from '@angular/core';
import { Http,Headers,RequestOptions } from '@angular/http';
import { DataSource } from './datasource';
import 'rxjs/add/operator/map';

@Injectable()
export class Servers {

  constructor(public http: Http,public datasource: DataSource) {}

  getData(){

    return this.http.get('http://localhost/ionic/server/public/api/data')
    .map(res => res);
 
  }

  create(item):any {
    let result:any;
    let headers = new Headers();
    
    headers.append('Content-Type','application/json');

    let option = new RequestOptions({headers: headers});

    this.http.post('http://localhost:80/ionic/server/public/api/data/create',JSON.stringify(item),option)
    .map(res => res )
    .subscribe(data =>{
          //console.log(data);  
          this.datasource.source.push(data.json());
     });

    //return result;
  }

  update(item):any {
    let result:any;
    let headers = new Headers();
    headers.append('Content-Type','application/json');

    this.http.put('http://localhost:80/ionic/server/public/api/data/update',JSON.stringify(item), { headers: headers })
    .map(res => res)
    .subscribe(data =>{
          result = data;  
     });

    return result;
  }


  delete(item):any {
    let result:any;
    let headers = new Headers();
    headers.append('Content-Type','application/json');

    this.http.delete('http://localhost/ionic/server/public/api/data/delete/'+item,{headers: headers})
    .map(res => res)
    .subscribe(data =>{
          result = data;  
     });

    return result;
  }

}

datasource.ts

import { Injectable } from '@angular/core';

@Injectable()
export class DataSource {

  public source:any[] = [];
  public tempdata:any = '';

}

and don't forget for app.module.ts , add your provider to this file

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HttpModule, JsonpModule } from '@angular/http';

import { CreatePage } from '../pages/create/create';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Servers } from '../providers/servers';
import { DataSource } from '../providers/datasource';


@NgModule({
  declarations: [
    MyApp,
    CreatePage,
    HomePage,
    TabsPage
  ],
  imports: [
    BrowserModule,
    HttpModule, //*
    JsonpModule, //*
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    Servers, //here
    DataSource, //here
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

step 3 : create new page [ listpage ]

  • list page you can use home-page from ionic project that already in your project page directory yourproject/src/pages/
import { Component } from '@angular/core';
import { NavController,NavParams } from 'ionic-angular';
import { Servers } from '../../providers/servers'; // service for crud with server side
import { DataSource } from '../../providers/datasource'; // to store data for view

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers:[Servers]
})
export class HomePage {

	public items: any;
  public toggle: boolean = false;
  public pastname: string;

  constructor(
   public navCtrl: NavController,
   public db: Servers,
   public navparam: NavParams,
   public datasource: DataSource) {
      this.db.getData().subscribe(data =>{
          this.datasource.source = data.json();  
      });
  }

  createItem(newitem){
    
      let i = { 'name': newitem.value };
      this.db.create(i);
    
  }

  deleteItem(item){
    let result = this.db.delete(item);
    let index = this.datasource.source.indexOf(item);
    this.datasource.source.splice(index,1);
    console.log(result);	
  }

  editItem(item){
    this.toggle = true;
    this.pastname = item.name;
    this.datasource.tempdata = item;
  }

  updateItem(name){
    let i = { "id": this.datasource.tempdata.id,"name": name.value };
    let result = this.db.update(i);
    let index = this.datasource.source.indexOf(this.datasource.tempdata);
    this.datasource.source[index] = i;
    console.log(result);
    this.toggle = false;
  }
}

then html page :

<!--home html page-->
<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list>
  <ion-item-sliding *ngFor="let item of datasource.source">
    <ion-item>
      {{ item.name }}
    </ion-item>
    <ion-item-options side="left">
      <button ion-button (click)="editItem(item)" >Edit</button>
      <button ion-button color="danger" (click)="deleteItem(item.id)">Delete</button>
    </ion-item-options>
  </ion-item-sliding>
</ion-list>
<hr/>
<ion-grid>
      <ion-input ngControl="name" placeholder="name" #name [ngModel]="pastname" ></ion-input>
      <button *ngIf="toggle == false" [style.display]="visible" ion-button (click)="createItem(name)">Add</button>
      <button *ngIf="toggle == true" [style.display]="visible" ion-button (click)="updateItem(name)">edit</button>
</ion-grid>
</ion-content>

that's it then you can try out .

Share this Post:

Related Posts:

www.000webhost.com