Слишком мало аргументов для функции App \ Http \ Controllers \ Admin \ AccountsController :: index (), 0 передано и ровно 1 ожидается в laravel

Сеанс уничтожается после успешного входа в систему или произошла ошибка охранника, который не смог сохранить сеанс. При запросе your_session_key в представлении панели инструментов он предоставляет null.

Route::group(['prefix' => 'admin'], function () {
Route::namespace('Admin')->group(function () {
Route::group(['middleware' => ['admin_middle','auth:admin']] , function () {
        Route::get('accounts/', 'AccountsController@index')->name('admin.accounts');
        });
    });
});

Промежуточное ПО: App \ Http \ Middleware \ RedirectIfNotAdmin // Зарегистрировано в ядре как 'admin_middle' => \ App \ Http \ Middleware \ RedirectIfNotAdmin :: class,

class RedirectIfNotAdmin
{
public function handle($request, Closure $next, $guard = 'admin')
{
    if (!auth()->guard($guard)->check()) {
        $request->session()->flash('error', 'You must be an Admin to see this page');
        return redirect(route('auth.admin.login'));
    }

    return $next($request);
}
}

Охрана: config / auth.php // Пользовательская охрана

'guards' => [
'admin' => [
    'driver' => 'session',
    'provider' => 'admin',

],
],

AccountsController: Controllers \ AccountsController

class AccountsController расширяет Controller {

public function __construct(AdminRepositoryInterface $adminRepository) {
    $this->adminRepo = $adminRepository;
}

private $adminRepo;
public function index(int $id)
{
    $admin = $this->adminRepo->findAdminById($id);

    $talentRepo = new AdminRepository($admin);


    return view('admin.accounts');
}

}

AdminRepositoryInterface: App \ Shop \ Admins \ Repositories \ Interfaces \ AdminRepositoryInterface;

interface AdminRepositoryInterface extends BaseRepositoryInterface
{
public function findAdminById(int $id) : Admin;
}

AdminRepository: App \ Shop \ Admins \ Repositories \ AdminRepository

class AdminRepository extends BaseRepository implements AdminRepositoryInterface
{
public function findAdminById(int $id) : Admin
{
    try {
        return $this->findOneOrFail($id);
    } catch (ModelNotFoundException $e) {
        throw new AdminNotFoundException($e);
    }
}
}

Просмотр: admin \ accounts.blade

@if (Session::has('YOUR_SESSION_KEY'))
{{-- do something with session key --}} 
@else
{{-- session key does not exist  --}} //this has been printed is the ID variable is not passed
@endif
{{$admin->name}}
 <br />{{$admin->email}}

person Naren    schedule 21.01.2020    source источник
comment
В вопросе много кода, который не имеет отношения к проблеме. @param AdminRepositoryInterface $adminRepository Объект adminRepo передается как параметр и игнорируется? Что вы собираетесь заполнить $this->adminRepo?   -  person AD7six    schedule 21.01.2020
comment
Я жду пользы от сеанса. @ AD7six   -  person Naren    schedule 21.01.2020
comment
Я думаю, вы неправильно поняли вопрос, Нарен.   -  person AD7six    schedule 21.01.2020
comment
Думаю, я немного понял. Я обновил код. Теперь это другая ошибка @ AD7six   -  person Naren    schedule 21.01.2020
comment
Не знаю, мне кажется, что с охраной какая-то ошибка. @ AD7six и промежуточное ПО. Пожалуйста, предложите что-нибудь.   -  person Naren    schedule 21.01.2020


Ответы (1)


Он говорит, что $this->adminRepo возвращает null.

Попробуйте инициализировать свой $this->adminRepo в конструкторе контроллера. Если вы набираете интерфейс, убедитесь, что вы привязали его к провайдеру услуг.

https://laravel.com/docs/5.8/container#binding-basics

person Thijs Banierink    schedule 21.01.2020
comment
$ this- ›app-› bind (AdminRepositoryInterface :: class, AdminRepository :: class); Да, привязал в Провайдерах - person Naren; 21.01.2020