Laravel8后相关Api的相关问题

之前都是有Laravel8架子,直接拿来用就好了,这次自己也想规范一点,那就从头记录一些知识吧!(不断更新中)

2022-07-11 05:49:15   2025-05-22 06:09:04   PHP   311 views  

 

路由定义问题(定义路由后找不到控制器)

Laravel8之前定义路由

 Route::post('/login', "UserController@store")
            ->name('users.login');

Laravel8之后定义路由

use App\Http\Controllers\UserController;

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

PS:当然也有简单的一劳永逸的办法

app/Providers中找到RouteServiceProviders

修改成以下代码即可使用主要在于定义namespace然后在boot中加入即可

<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "home" route for your application.
     *
     * This is used by Laravel authentication to redirect users after login.
     *
     * @var string
     */
    public const HOME = '/';

    /**
     * The controller namespace for the application.
     *
     * When present, controller route declarations will automatically be prefixed with this namespace.
     *
     * @var string|null
     */
    protected $namespace = 'App\\Http\\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));
        });
    }

    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
        });
    }
}

接口返回信息问题(接口返回大量html代码并且表单验证错误会重定向)

之前也没太关注过返回信息,因为不太爱用验证器,现在想规范一点使用验证器,今天突然发现返回的是一个重定向链接,不是以往的错误信息,仔细研究了一下,原来是Laravel会根据请求头信息来返回响应的数据,以下是接口设置请求头一劳永逸的解决办法。

设置默认Accept头

Accept 这个头非常重要,决定了响应返回的格式,设置为 application/json 你遇到的所有报错,Laravel 会默认帮你处理为 Json 的格式。

但是这个头必须是客户端进行接口调用的时候设置,当有些时候客户端无法正确设置的时候,有没有办法默认就返回 Json 格式的响应呢。

其实我们可以添加一个中间件,给所有的 API 路由手动设置一下。

php artisan make:middleware AcceptHeader

app/Http/Middleware/AcceptHeader.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class AcceptHeader
{
    public function handle(Request $request, Closure $next)
    {
        $request->headers->set('Accept', 'application/json');

        return $next($request);
    }
}

代码非常简单,就是给请求添加一个 Accept 的头。

app/Http/Kernel.php

.
.
.
    protected $middlewareGroups = [
        'web' => [
       .
       .
       .
        ],
        'api' => [
            \App\Http\Middleware\AcceptHeader::class,
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];
.
.
.

最后在 api 中间件组中添加上这个中间件即可。

测试一下

file