我花了一段时间试图弄明白这一点,但我没有找到决定性的解决方案。基本上,我试图根据登录的用户检索客户端列表,但除了
index()
函数where is返回视图,以及显示登录用户名的刀片模板。
这是我的客户端控制器。php:
<?php
namespace App\Http\Controllers;
use App\Http\Models\Client;
use App\Http\Requests\GetClientsRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class ClientController extends Controller
{
protected $user;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
}
/**
* Show the clients page.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
Log::info("client user: " . print_r($this->user, 1));
return view('page');
}
public function getClients()
{
$currentUser = Auth::user();
if ($currentUser) {
$clients = Client::with('account')
->where('user_id', $currentUser->account)
->get();
$collection = collect($clients);
return response($collection->toArray());
}
}
}
索引函数中的Log打印出用户对象没有问题,但是在
getClients()
函数,它是空的。我也试着在
__construct()
:
$this->middleware('auth');
根据我使用的Laravel模板,但是每当我调用
getClients
API路由我总是收到401未经授权的错误。
这是我的
api.php
路由文件(尽管当前仅使用getClients调用):
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get('welcome-message', 'DashboardController@getWelcomeMessage');
Route::prefix('clients')->group(function () {
Route::get('/', 'ClientController@getClients');
Route::get('/{clientId}', 'ClientController@getClient');
Route::post('/', 'ClientController@postCreateClient');
Route::put('/{clientId}', 'ClientController@putUpdateClient');
});
还有我的
web.php
路由文件:
<?php
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();
Route::get('/', 'HomeController@index')->name('dashboard');
Route::get('/clients', 'ClientController@index')->name('clients');
系统知道我已登录,因为我甚至无法访问客户端仪表板,所以我不明白为什么我无法从
Auth::user()
在函数中-除非我不正确地使用中间件?