ステップチュートリアルで


もともとhttps://codeanddeploy.com訪問し、サンプルコードをダウンロードしてください
この記事では、ステップバイステップチュートリアルで、Laravel 8 Ajaxの例を実装する方法を紹介します.この例では、サーバーに要求するたびに更新されないアプリケーションを作成する方法の基本的な方法を理解するのに役立ちます.このメソッドは、サーバーの帯域幅コストを低減し、ユーザーエクスペリエンスを向上させるのに役立ちます.

https://codeanddeploy.com/blog/laravel/laravel-8-ajax-example-step-by-step-tutorial Ajaxプログラミングとは何か


Ajaxは、クライアント側に多数のWebテクノロジを使用して非同期アプリケーションを作成するWebプログラミング技術のセットです.AJAXでは、Webアプリケーションは、ページをリフレッシュせずにサーバーからデータを非同期で要求して取得できます.

8 Ajaxの例


さて、AJAXをLALAVEL 8アプリケーションに適用しましょう.我々は、Ajaxを使用してテーブルを介してデータを作成し、取得できる簡単なプロジェクト管理を作成します.

ステップ1:ラーラベルインストール


起動する前に、ローカル環境にララーブ8アプリケーションをインストールする必要があります.この例では、Windows経由でXAMPPを使用しています.しかし、あなたは自由に任意のマシンとOSを使用します.htdocsフォルダにこのコマンドを実行します.
composer create-project laravel/laravel laravel-ajax-example --prefer-dist
コマンドを実行すると、LALAVEL 8プロジェクトディレクトリを指すコマンドを実行します.
cd laravel-ajax-example

ステップ2:データベース構成


あなたのLaravelプロジェクトが新鮮な場合は、データベースの資格情報を更新する必要があります.ジャストオープン.Lavavel 8プロジェクトのEnvファイル..env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here

ステップ3 :モデル、コントローラ、およびマイグレーションを生成する


Laravel Ajaxの例では、モデル、コントローラ、および移動を生成するには、次のコマンドを実行します.
php artisan make:model Project -m -c

ステップ4 :移行設定


以下の例のコード表を参照してください.
<?php

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

class CreateProjectsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('projects', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('projects');
    }
}
次のコマンドを実行します.
php artisan migrate

ステップ5:セットアップモデル


こちらがプロジェクトのコードです.PHPモデル.
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 
        'description'
    ];
}

ステップ6 :セットアップコントローラ


以下はProjectControllerのコードです.PHPでは、成功したリクエストに応答して応答を使用していることがわかります.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Project;
use Response;

class ProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     */
    public function index()
    {
        $projects = Project::orderBy('id','desc')->get();
        return view('projects.index')->with(compact('projects'));
    }

    /**
     * Store a newly created resource in storage.
     *
     */
    public function store(Request $request)
    {
        $data = $request->validate([
            'title' => 'required',
            'description' => 'required'
        ]);

        $project = Project::create($data);

        return Response::json($project);
    }
}

ステップ7:セットアップルート


以下のコードは私たちのルートです.
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProjectController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', [ProjectController::class, 'index']);

Route::resource('projects', ProjectController::class);

ステップ8 :プロジェクトのレイアウトを作成する


次に、[リソース]をクリックし、[プロジェクトフォルダー]を作成します.次にインデックスを作成します.ブレード.PHP
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>Laravel Ajax Example</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">

    <style type="text/css">
        /* Custom page CSS
        -------------------------------------------------- */
        /* Not required for template or sticky footer method. */

        main > .container {
          padding: 60px 15px 0;
        }
    </style>
</head>

<body class="d-flex flex-column h-100">

    <header>
        <!-- Fixed navbar -->
        <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
            <div class="container-fluid">
                <a class="navbar-brand" href="#">Fixed navbar</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarCollapse">
                    <ul class="navbar-nav me-auto mb-2 mb-md-0">
                        <li class="nav-item">
                            <a class="nav-link active" aria-current="page" href="#">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#">Link</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link disabled">Disabled</a>
                        </li>
                    </ul>
                    <form class="d-flex">
                        <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
                        <button class="btn btn-outline-success" type="submit">Search</button>
                    </form>
                </div>
            </div>
        </nav>
    </header>


    <!-- Begin page content -->
    <main class="flex-shrink-0">
        <div class="container">
            <h1 class="mt-5">Laravel Ajax Example <a href="javascript:void(0)" class="btn btn-primary" style="float: right;"  data-bs-toggle="modal" data-bs-target="#add-project-modal">Add Project</a></h1>

            <table class="table" id="projects-table">
                <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Title</th>
                        <th scope="col">Description</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($projects as $project)
                        <tr>
                            <th scope="row">{{ $project->id }}</th>
                            <td>{{ $project->title }}</td>
                            <td>{{ $project->description }}</td>
                        </tr>
                    @endforeach

                </tbody>
            </table>

        </div>
    </main>

    <!-- The Modal -->
    <div class="modal" id="add-project-modal">
        <div class="modal-dialog">
            <div class="modal-content">

                <!-- Modal Header -->
                <div class="modal-header">
                    <h4 class="modal-title">Add Project</h4>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form data-action="{{ route('projects.store') }}" method="POST" enctype="multipart/form-data" id="add-project-form">
                    <!-- Modal body -->
                    <div class="modal-body">
                        @csrf
                        <div class="mb-3">
                            <label for="title" class="form-label">Title</label>
                            <input type="text" class="form-control" id="title" placeholder="Title" name="title">
                        </div>

                        <div class="mb-3">
                            <label for="description" class="form-label">Description</label>
                            <input type="text" class="form-control" id="description" placeholder="Description" name="description">
                        </div>
                    </div>

                    <!-- Modal footer -->
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">Save</button>
                        <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
                    </div>

                </form>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
    <script src="{{ asset('js/projects.js') }}" defer></script>

</body>

</html>

ステップ9 : Ajax用のJavaScriptを作成する


この節では、すでに存在している場合はpublicの内部にJSフォルダを作成する必要があります.js
$(document).ready(function(){

    var table = '#projects-table';
    var modal = '#add-project-modal';
    var form = '#add-project-form';

    $(form).on('submit', function(event){
        event.preventDefault();

        var url = $(this).attr('data-action');

        $.ajax({
            url: url,
            method: 'POST',
            data: new FormData(this),
            dataType: 'JSON',
            contentType: false,
            cache: false,
            processData: false,
            success:function(response)
            {
                var row = '<tr>';
                    row += '<th scope="row">'+response.id+'</th>';
                    row += '<td>'+response.title+'</td>';
                    row += '<td>'+response.title+'</td>';
                row += '</tr>';

                $(table).find('tbody').prepend(row);


                $(form).trigger("reset");
                $(modal).modal('hide');
            },
            error: function(response) {
            }
        });
    });

});
次のコマンドを実行するのを忘れないでください.
php artisan serve

さて、上記のチュートリアルを実行した後、Laravel 8 Ajaxをどのように実装するかについての基本的な考え方があります.
私はこのチュートリアルを助けることを望む.あなたがこのコードをダウンロードしたいならば、親切にをここで訪問してください.
ハッピーコーディング