在laravel 5.5中,中间件修改不会保存到数据库中

时间:2017-12-01 13:36:15

标签: php laravel middleware

在laravel 5.5中,我想在提交表单时为我的字符串值进行解决。

为此,我创建了中间件app / Http / Middleware / WorkTextString.php:

<?php

namespace App\Http\Middleware;

use Closure;
use App\Http\Traits\funcsTrait;
use function PHPSTORM_META\type;

class WorkTextString
{

    use funcsTrait;
    public function handle($request, Closure $next)
    {
        $request->name = $this->workTextString($request->name); // Fields I want to modify
        $request->description = $this->workTextString($request->description);

        return $next($request);
    }

    protected function workTextString($str) // my workout for any string
    { // some string routing, like trimming more 2 spaces inside of string
    ...

并在app / Http / Kernel.php中添加了我的中间件:

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,
    'WorkTextString'=>\App\Http\Middleware\WorkTextString::class,
];

在routes / api.php中:

Route::group([  'prefix' => '/v1', 'namespace' => 'Api\V1', 'as' => 'api.'], function () {

    Route::resource('user_task_types', 'UserTaskTypesController', ['except' => ['create', 'edit']])->middleware('WorkTextString');

因为我看到我的中间件被触发,但修改没有保存到db。 哪种方法正确?

谢谢!

1 个答案:

答案 0 :(得分:1)

我猜你想要更新请求中的数据。您可以尝试合并新数据:

$request->merge([
    'name' => $this->workTextString($request->name),
    'description' => $this->workTextString($request->description),
]);

或者

$request['name'] = $this->workTextString($request->name);
$request['description'] = $this->workTextString($request->description);

Request没有__set方法,因此在尝试设置属性时,您实际上并未设置任何实际用作输入源的变量{\ n} { {1}};

虽然仍然不确定你的代码的哪一部分与数据库有关。