目标类 [UserController] 不存在 Laravel 8

Posted

技术标签:

【中文标题】目标类 [UserController] 不存在 Laravel 8【英文标题】:Target class [UserController] does not exist Laravel 8 【发布时间】:2021-04-09 21:19:45 【问题描述】:

我在访问控制器的路径上有问题,我已将 laravel 项目版本 5 复制到我在 laravel 版本 8 中的项目中,我已将我的 laravel 项目中的文件 RouteServiceProvider.php 更改为此

protected $namespace = 'App\Http\Controllers';

    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'));
        );
    

但仍然无法正常工作,错误消息显示“Illuminate\Contracts\Container\BindingResolutionException 目标类 [UserController] 不存在。”

这是 web.php 代码

<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () 
return view('welcome');
);

// Auth::routes();

// Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/', [HomeController::class, 'index'])->name('home');

Auth::routes();

Route::group(['middleware' => 'web'], function()
   Route::get('user/profil', 'App\Http\Controllers\UserController@profil')->name('user.profil');
   Route::patch('user/id/change', 'App\Http\Controllers\UserController@changeProfil');

   Route::get('transaksi/baru', 'App\Http\Controllers\PenjualanDetailController@newSession')->name('transaksi.new');
   Route::get('transaksi/id/data', 'App\Http\Controllers\PenjualanDetailController@listData')->name('transaksi.data');
   Route::get('transaksi/cetaknota', 'App\Http\Controllers\PenjualanDetailController@printNota')->name('transaksi.cetak');
   Route::get('transaksi/notapdf', 'App\Http\Controllers\PenjualanDetailController@notaPDF')->name('transaksi.pdf');
   Route::post('transaksi/simpan', 'App\Http\Controllers\PenjualanDetailController@saveData');
   Route::get('transaksi/loadform/diskon/total/diterima', 'App\Http\Controllers\PenjualanDetailController@loadForm');
   Route::resource('transaksi', 'App\Http\Controllers\PenjualanDetailController');
);

这是例如控制器

<?php

namespace App\Http\Controllers;
use \Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;

use Auth;
use Hash;
class UserController extends Controller

   public function index()
   
      return view('user.index'); 
   

   public function listData()
   
   
     $user = User::where('level', '!=', 1)->orderBy('id', 'desc')->get();
     $no = 0;
     $data = array();
     foreach($user as $list)
       $no ++;
       $row = array();
       $row[] = $no;
       $row[] = $list->name;
       $row[] = $list->email;
       $row[] = '<div class="btn-group">
               <a onclick="editForm('.$list->id.')" class="btn btn-primary btn-sm"><i class="fa fa-pencil"></i></a>
               <a onclick="deleteData('.$list->id.')" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></a></div>';
       $data[] = $row;
     

     $output = array("data" => $data);
     return response()->json($output);
   

   public function store(Request $request)
   
      $user = new User;
      $user->name = $request['nama'];
      $user->email = $request['email'];
      $user->password = bcrypt($request['password']);
      $user->level = 2;
      $user->foto = "user.png";
      $user->save();
   

   public function edit($id)
   
     $user = User::find($id);
     echo json_encode($user);
   

   public function update(Request $request, $id)
   
      $user = User::find($id);
      $user->name = $request['nama'];
      $user->email = $request['email'];
      if(!empty($request['password'])) $user->password = bcrypt($request['password']);
      $user->update();
   

   public function destroy($id)
   
      $user = User::find($id);
      $user->delete();
   

   public function profil()
   
      $user = Auth::user();
      return view('user.profil', compact('user')); 
   

   public function changeProfil(Request $request, $id)
   
      $msg = "succcess";
      $user = User::find($id);
      if(!empty($request['password']))
        if(Hash::check($request['passwordlama'], $user->password))
         $user->password = bcrypt($request['password']);
        else
         $msg = 'error';
        
       

      if ($request->hasFile('foto')) 
         $file = $request->file('foto');
         $nama_gambar = "fotouser_".$id.".".$file->getClientOriginalExtension();
         $lokasi = public_path('images');

         $file->move($lokasi, $nama_gambar);
         $user->foto         = $nama_gambar;  
         
         $datagambar = $nama_gambar;
      else
         $datagambar = $user->foto; 
      

      $user->update();
      echo json_encode(array('msg'=>$msg, 'url'=> asset('public/images/'.$datagambar))); 
   


这是 user.profil.blade 的刀片视图,例如

@extends('layouts.app')

@section('title')
  Edit Profil
@endsection

@section('breadcrumb')
   @parent
   <li>user</li>
   <li>edit profil</li>
@endsection

@section('content')     
<div class="row">
  <div class="col-xs-12">
    <div class="box">

 <form class="form form-horizontal" data-toggle="validator" method="post" enctype="multipart/form-data">
    csrf_field()   method_field('PATCH') 
   <div class="box-body">

  <div class="alert alert-info alert-dismissible" style="display:none">
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
    <i class="icon fa fa-check"></i>
    Perubahan berhasil disimpan.
  </div>

 <div class="form-group">
    <label for="foto" class="col-md-2 control-label">Foto Profil</label>
    <div class="col-md-4">
      <input id="foto" type="file" class="form-control" name="foto">
      <br><div class="tampil-foto"> <img src=" asset('public/images/'.Auth::user()->foto) " ></div>
    </div>
  </div>

  <div class="form-group">
      <label for="passwordlama" class="col-md-2 control-label">Password Lama</label>
      <div class="col-md-6">
         <input id="passwordlama" type="password" class="form-control" name="passwordlama">
         <span class="help-block with-errors"></span>
      </div>
   </div>

  <div class="form-group">
      <label for="password" class="col-md-2 control-label">Password</label>
      <div class="col-md-6">
         <input id="password" type="password" class="form-control" name="password">
         <span class="help-block with-errors"></span>
      </div>
   </div>

   <div class="form-group">
      <label for="password1" class="col-md-2 control-label">Ulang Password</label>
      <div class="col-md-6">
         <input id="password1" type="password" class="form-control" data-match="#password" name="password1">
         <span class="help-block with-errors"></span>
      </div>
   </div>

  </div>
  <div class="box-footer">
    <button type="submit" class="btn btn-primary pull-right"><i class="fa fa-floppy-o"></i> Simpan Perubahan</button>
  </div>
</form>
    </div>
  </div>
</div>
@endsection

@section('script')
<script type="text/javascript">
$(function()
    $('#passwordlama').keyup(function()
      if($(this).val() != "") $('#password, #password1').attr('required', true);
      else $('#password, #password1').attr('required', false);
    );

   $('.form').validator().on('submit', function(e)
      if(!e.isDefaultPrevented()) 

         $.ajax(
           url : " Auth::user()->id /change",
           type : "POST",
           data : new FormData($(".form")[0]),
           dataType: 'JSON',
           async: false,
           processData: false,
           contentType: false,
           success : function(data)
             if(data.msg == "error")
               alert('Password lama salah!');
               $('#passwordlama').focus().select();
             else
               d = new Date();
               $('.alert').css('display', 'block').delay(2000).fadeOut();
               $('.tampil-foto img, .user-image, .user-header img').attr('src', data.url+'?'+d.getTime());
             
           ,
           error : function()
             alert("Tidak dapat menyimpan data!");
              
         );
         return false;
     
   );

);

</script>
@endsection

【问题讨论】:

错误说当你做什么?看来您也更改了所有路线 【参考方案1】:

您遇到错误是因为您在 web.php 文件中的每个路由上定义控制器命名空间(例如 'App\Http\Controllers\UserController@profil')以及为RouteServiceProvider.php 中的 protected $namespace 变量(例如 protected $namespace = 'App\Http\Controllers';)。

现在您需要做的是在 web.php 文件中的每个路由上定义控制器命名空间,或者在 RouteServiceProvider.php 中为受保护的 $namespace 变量提供值

你不能同时做这两件事。只需选择最适合您情况的套件。 要么从 RouteServiceProvider.php 文件中删除 protected $namespace = 'App\Http\Controller';,要么删除你在 web.php 文件中的每个路由附加的控制器命名空间。 (将Route::get('user/profil', 'App\Http\Controllers\UserController@profil')-&gt;name('user.profil'); 更改为Route::get('user/profil', 'UserController@profil')-&gt;name('user.profil');),一切正常。

有关 Laravel 文档参考,您可以阅读 https://laravel.com/docs/8.x/upgrade#routing

但是很多人会得到这个错误,因为他们习惯于定义他们的路线,比如 Route::get('/users','UserController@index); 并且在 Laravel 7 之前的版本中以这种方式定义它很好。但是 Laravel 8 改变了这种方法,而是提供了定义路由的新方法。

使用 PHP 可调用语法 Route::get('/users', [UserController::class, 'index']); 通过这种方式,您需要将控制器文件导入 web.php

使用字符串语法,即Route::get('/users', 'App\Http\Controllers\UserController@index');

【讨论】:

以上是关于目标类 [UserController] 不存在 Laravel 8的主要内容,如果未能解决你的问题,请参考以下文章

目标类 [UserController] 不存在 Laravel 8

类 App\Http\Controllers\API\UserController 不存在

“方法 App\Http\Controllers\API\UserController::show 不存在

App\Http\Controllers\User\UserController::me@index 不存在

目标类 [App\\Http\\EnsureFrontendRequestsAreStateful] 不存在

“目标类 [Modules\\Admins\\Controllers\\AdminController] 不存在。”