首页 > 解决方案 > 带有哈希值的 url id 掩码:未配置连接 [App\User]

问题描述

我正在关注 ben sampo 关于 url 屏蔽的教程,并且收到错误连接 [App\User] 未配置。

配置中的 app.php

        'Hashids' => Vinkla\Hashids\Facades\Hashids::class,

hashids.php

 'connections' => [

    'main' => [
        'salt' => 'your-salt-string',
        'length' => 'your-length-integer',
    ],

    'alternative' => [
        'salt' => 'your-salt-string',
        'length' => 'your-length-integer',
    ],
    \App\User::class => [
        'salt' => \App\User::class.'7623e9b0009feff8e024a689d6ef59ce',
        'length' => 5,
    ],

],

网页.php

Route::get('/home/{user}', 'HomeController@index')->name('home');

特征 hashidable.php

 <?php
namespace App\Http\Traits;
trait Hashidable
{
    public function getRouteKey()
    {
        return \Hashids::connection(get_called_class())->encode($this->getKey());
    }
}

用户.php

 use Hashidable;

RouteServiceProvider.php

 public function boot()
{
    parent::boot();

    
    Route::bind('user', function ($value, $route) {
        return $this->getModel(\App\User::class, $value);
    });
}
    // added by rap
    private function getModel($model, $routeKey)
{
    $id = \Hashids::connection($model)->decode($routeKey)[0] ?? null;
    $modelInstance = resolve($model);

    return  $modelInstance->findOrFail($id);
}

标签: phplaravelurl

解决方案


我有同样的问题,这些是我的代码。

我没有放入 app.php

'Hashids' => Vinkla \ Hashids \ Facades \ Hashids :: class,

我的文件 hashids.php

'connections' => [

    \App\Models\User::class => [
        'salt' => \App\Models\User::class.'fe4898dfe2fb8422f6dc8f79146d214d',
        'length' => 10,
    ],
    \App\Models\Course::class => [
        'salt' => 
  \App\Models\Course::class.'6dc29bf420a127578beaacab45f41351',
        'length' => 8,
    ],
    \App\Models\Unit::class => [
        'salt' => \App\Models\Unit::class.'c91a52c63222c1080a104b21f3331a60',
        'length' => 12,
    ],

],

我的特征文件和你的一样,我的文件 RouteServiceProvider.php

public function boot()
{
    parent::boot();

    Route::bind('user', function ($value, $route) {
        return $this->getModel(User::class, $value);
    });

    Route::bind('unit', function ($value, $route) {
        return $this->getModel(Unit::class, $value);
    });

    Route::bind('course', function ($value, $route) {
        return $this->getModel(Course::class, $value);
    });
}

protected function getModel($model, $routeKey) {
    $id = \Hashids::connection($model)->decode($routeKey)[0] ?? null;
    $modelInstance = resolve($model);
    return $modelInstance->findOrFail($id);
}

解决方案就是运行这个命令php artisan config:clear我有同样的问题,这解决了一切

解决了未配置的哈希值


推荐阅读