Как использовать Angular с Laravel для начинающих

Чтобы использовать Angular с Laravel, вы можете создать внешний интерфейс в Angular и создать внутренний API в Laravel с базами данных MySQL или NoSQL. Мы создаем внешний интерфейс приложения Angular, а затем вызываем API для хранения данных. Это просто базовое приложение для хранения предметов, использующее Angular и Laravel.

Во-первых, мы настроим проект Angular на стороне клиента. Для этого вы можете использовать angular-cli  для шаблона для нашего приложения.

Настройте Angular Environment.

Во-первых, нам нужно установить Angular CLI глобально. Итак, введите следующую команду.

npm install -g @angular/cli

Хорошо, теперь нам нужно создать один проект; назовем его ng4tutorial.

Введите следующую команду в терминале.

ng new ng4tutorial

Он создаст файлы и папки и установит все интерфейсные зависимости.

После установки введите следующую команду.

cd ng4tutorial
ng serve --open

Создайте одну форму для ввода данных.

Угловой является модульным. Все файлы компонентов находятся в  папке src >> app .

Мы используем Bootstrap CSS Framework для разработки нашей формы. Итак, я загрузил CSS-файл начальной загрузки в каталог ресурсов src >>  с именем  app.css  .

Наш  файл index.html  выглядит так.

<!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>

Все общедоступные статические файлы обслуживаются из  папки с ресурсами  .

Для создания формы нам нужно изменить  файл app.component.html  . Этот файл находится в каталоге src   >>   app .

<!--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>

Наш  файл app.component.ts  выглядит так.

// 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';
}

Наша форма выглядит так.

Учебное пособие по Laravel AngularJS

Обработайте входные данные.

Во-первых, нам нужно импортировать два модуля в файл app.module.ts  .

  1. ФормыМодуль
  2. HttpModule

И эти модули также включены в  массив импорта  . Итак, наш  файл src >> app >> app.module.ts  выглядит так.

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

Теперь нам нужно включить объект Angular  Form  в наш HTML. Наш окончательный код  app.component.ts  выглядит так.

// 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>

Мы добавили один атрибут в поле ввода под названием « ngModel ». Этот атрибут сообщает angular, сколько значений есть в HTML-форме. Итак, сначала он создает объект, а позже, после его отправки, мы можем получить к нему доступ и получить значения.

<form (ngSubmit)="onSubmit(fm)" #fm="ngForm">

Это способ сообщить AngularJS, что ему нужно создать объект, описывающий весь элемент формы и его значения.

После нажатия кнопки submit вызывается функция onSubmit()  , и в ней мы можем получить все значения формы.

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

Здесь функция onSubmit() , мы получаем все значения формы. Теперь мы можем отправить  запрос POST  на сервер Laravel .

Отправьте данные на сервер Laravel.

Следующим шагом будет вызов службы HTTP для обработки запроса POST .

Во-первых, нам нужно импортировать два модуля в файл app.component.ts  .

import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/toPromise';

Следующим шагом будет вызов этой службы. Это мой полный код  файла app.component.ts  .

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

Я использовал Promise и Observables. Я также импортировал его в Топ.

Создайте бэкэнд Laravel для запроса.

Создайте один проект Laravel, введя следующую команду.

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

Отредактируйте . env  для установки учетных данных базы данных MySQL.

Затем переключитесь в интерфейс командной строки и введите следующую команду.

php artisan make:model Item -m

Перейдите к файлу миграции в базе данных   >>   миграции   >>   create_items_table  и скопируйте в него следующий код.

<?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');
    }
}

Введите следующую команду в терминале.

php artisan migrate

Создайте один контроллер с именем  ItemController.

php artisan make:controller ItemController

Зарегистрируйте маршруты в  файле route >> api.php  .

Route::post('items', 'ItemController@store');

В  модели Item.php  нам нужно включить свойство $fillable , чтобы предотвратить исключения массового присваивания.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    protected $fillable = ['name', 'price'];
}

Напишите функцию хранения в файле ItemController.php  , чтобы сохранить данные в базе данных.

<?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');
    }
}

Запустите сервер разработки Laravel, введя следующую команду.

php artisan serve

Решить проблему CORS

Загрузите следующий пакет CORS для Laravel, чтобы избежать этой проблемы, и следуйте инструкциям.

composer require barryvdh/laravel-cors

Сначала добавьте Cors\ServiceProvider в массив вашего провайдера.

Barryvdh\Cors\ServiceProvider::class,

Чтобы разрешить CORS для всех ваших маршрутов, добавьте  HandleCors промежуточное ПО в  $middleware свойство  app/Http/Kernel.phpclass:

protected $middleware = [
    // ...
    \Barryvdh\Cors\HandleCors::class,
];

Вы можете опубликовать конфигурацию с помощью этой команды:

php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

Теперь попробуйте еще раз; он сохранит данные в базу данных. Я не устанавливал перенаправление после сохранения данных, но установлю его коротким, пока вы проверяете значения базы данных.

Это основной пример Laravel Angular Example.

What is GEEK

Buddha Community

Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Lilyan  Streich

Lilyan Streich

1599764280

Laravel Angular Example | How To Use Angular And Laravel

Laravel Angular Tutorial Example From Scratch is today’s topic. Laravel is a PHP Web Application Framework. Angular is the 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 Application and then call an API to store the data. This is just a basic Item Storage Application using Angular and Laravel. 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.

Overview of Laravel Angular Project

  • Step 1: Setup Angular project.
  • Step 2: Create a form using Angular forms.
  • Step 3: Handle the input data coming from the form using Angular.
  • Step 4: Send the form data to Laravel server.
  • Step 5: Create Laravel backend: create table, views, controllers, models.
  • Step 6: Resolve cors problem. You can finally able to save the data to the database.

#laravel #angular #angular and laravel #php

Juned Ghanchi

1621508419

Laravel App Development Company in India, Hire Laravel Developers

Hire our expert team of Laravel app developers for flexible PHP applications across various cloud service providers.

With this easy build technology, we develop feature-rich apps that make your complex business process a lot easier. Our apps are,

  • More secure and scalable.
  • A good framework lets you manage and organize resources better.
  • And have a rich community base.

Get your business a best in classlaravel app. Hire laravel app developers in India. We have the best organizational set-up to provide you the most advanced app development services.

#laravel app development company india #hire laravel developers india #laravel app development company #hire laravel developers #laravel development agency #laravel app programmers

Seamus  Quitzon

Seamus Quitzon

1593060000

Angular 9 select2 with laravel 7.2 backend data

1. Very first, you need to below command into your Angular 9 application:

npm install select2
 npm install jquery --save

2. Now you need to add below code into your angular.json file:

 "styles": [
       "node_modules/select2/dist/css/select2.min.css",
              ...
          ],
"scripts": [
       "node_modules/jquery/dist/jquery.min.js", 
       "node_modules/select2/dist/js/select2.min.js"
              ...
      ]

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

...
import { HttpClientModule } from '@angular/common/http';
...
imports: [

  HttpClientModule,
  ...
  ],

#angular 8 #angular 9 #laravel 7 #laravel 7.2 #laravel