1646569800
Чтобы использовать Angular с Laravel, вы можете создать внешний интерфейс в Angular и создать внутренний API в Laravel с базами данных MySQL или NoSQL. Мы создаем внешний интерфейс приложения Angular, а затем вызываем API для хранения данных. Это просто базовое приложение для хранения предметов, использующее Angular и Laravel.
Во-первых, мы настроим проект Angular на стороне клиента. Для этого вы можете использовать angular-cli для шаблона для нашего приложения.
Во-первых, нам нужно установить 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';
}
Наша форма выглядит так.
Во-первых, нам нужно импортировать два модуля в файл app.module.ts .
И эти модули также включены в массив импорта . Итак, наш файл 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 .
Следующим шагом будет вызов службы 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, введя следующую команду.
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 для Laravel, чтобы избежать этой проблемы, и следуйте инструкциям.
composer require barryvdh/laravel-cors
Сначала добавьте Cors\ServiceProvider в массив вашего провайдера.
Barryvdh\Cors\ServiceProvider::class,
Чтобы разрешить CORS для всех ваших маршрутов, добавьте HandleCors
промежуточное ПО в $middleware
свойство app/Http/Kernel.php
class:
protected $middleware = [
// ...
\Barryvdh\Cors\HandleCors::class,
];
Вы можете опубликовать конфигурацию с помощью этой команды:
php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
Теперь попробуйте еще раз; он сохранит данные в базу данных. Я не устанавливал перенаправление после сохранения данных, но установлю его коротким, пока вы проверяете значения базы данных.
Это основной пример Laravel Angular Example.
1595201363
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'
];
}
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
1598940617
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.
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!!!
For Installing Angular on your Machine, there are 2 prerequisites:
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.
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:
· After executing the command, Angular CLI will get installed within some time. You can check it using the following command
Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:
To create a workspace:
#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli
1599764280
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.
#laravel #angular #angular and laravel #php
1621508419
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,
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
1593060000
npm install select2
npm install jquery --save
"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"
...
]
...
import { HttpClientModule } from '@angular/common/http';
...
imports: [
HttpClientModule,
...
],
#angular 8 #angular 9 #laravel 7 #laravel 7.2 #laravel