An empty bottle

しがないメンヘラエンジニアの日記。

【Laravel5.4】laravel de ajax【ajax苦労した。】

はじめに

「そんなこと知っとるわ」って言わないでね。

routes

まず、通常のアクセス(通常のGETやPOST、CRUDによるPUT、DELETE)はweb.phpに書くとして、
apiajaxに関してはapi.phpに記載したいと思った。

で、api.phpに飛ばすためには、 /api/hogehoge とprefixを「api」にすりゃいいのよね。

ルーティング 5.5 Laravel

routes/api.php

<?php

Route::group(['middleware' => ['web.ajax']], function () {
    // 設定ファイル /app/Http/Middleware/AjaxOnlyMiddleware.php
    
    Route::post('/getsubmenu/{id}', 'MenuMasterComtroller@getSubMenu');
});

AjaxOnlyMiddleware.php

routes/api.php にて、「ajaxのみ通信許可すっぜ!」という処理を追加しましょう。 こういった通信制限はroutesでやっちゃいたいですね。

api.phpの中にmiddlewareを作っちゃいましょう。

$ php artisan make:middleware AjaxOnlyMiddleware

これで、

app/Http/Middleware/AjaxOnlyMiddleware.php

ができちゃうね。

中身はこうしよう。 簡単だね、$request->ajax() で判定できちゃうね。

<?php

namespace App\Http\Middleware;

use Closure;

class AjaxOnlyMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($request->ajax() === true)
        {
            return $next($request);
        }
        else 
        {
            abort(404,'is not ajax!!!!');
        }
    }
}

Kernel.php

app/Http/Kernel.php だす。

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
        
        'web.auth' => [
            \App\Http\Middleware\Auth::class,
        ],
        
        // ↓ここ!!!!!
        'web.ajax' => [
            \App\Http\Middleware\AjaxOnlyMiddleware::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}

実際のjs

ここでは、selectboxで選択したdata-要素を渡す設定。

<script>
    
$(document).ready(function() 
{

    $('select').change(function() 
    {
            
        //選択したvalue値を変数に格納
        var val = $(this).val();
        val = $('select option:selected').data('menuid');
        
        $.ajax({
            type: 'POST',
            url: '/api/getsubmenu/' + val,
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            },
            dataType: 'json',
            success: function(data)
            {
                console.log(data);
            },
            error: function(XMLHttpRequest,textStatus,errorThrown) // 接続が失敗
            {
                console.log(textStatus);
                alert('It is error!!'); // エラーメッセージ
            }
        });
        return false;
        
    });
});

</script>