大家好,我在表演功能上遇到了很大的问题。我不知道问题是什么..我收到此错误“试图获取非对象的属性'id'”
ConversationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
use App\Repository\ConversationRepository;
use Illuminate\Auth\AuthManager;
class ConversationsController extends Controller
{
private $r;
private $auth;
public function __construct(ConversationRepository $conversationRepository, AuthManager $auth){
$this->r= $conversationRepository;
$this->auth=$auth;
}
public function index () {
return view('conversations/index' , ['users'=> $this->r->getConversations($this->auth->user()->id)]);
}
public function show (User $user) {
return view('conversations/show',[
'users'=> $this->r->getConversations($this->auth->user()->id),
'user' => $user
]) ;
}
public function store(User $user){
$this->r->createMessage(
$request->get('content'),
$this->auth->user()->id,
$user->id
);
return redirect(route('conversations.show', ['id'=> $user->id]));
}
}
?>
web.php
<?php
//use Illuminate\Routing\Route;
//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!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'ConversationsController@index')->name('home');
Route::get('/conversations', 'ConversationsController@index')->name('conversations');
Route::get('/conversations/{user}', 'ConversationsController@show')->name('conversations.show');
Route::post('/conversations/{user}', 'ConversationsController@store');
enter image description here ConversationRepository.php
<?php
namespace App\Repository;
use App\User;
use App\Message;
class ConversationRepository {
private $user;
private $message;
public function __construct(User $user, Message $message){
$this ->user = $user;
$this->message= $message;
}
public function getConversations(int $userId){
return $this->user->newQuery()
->select('name', 'id')
->where('id', '!=', $userId)
->get();
}
public function createMessage (string $content, int $from, int $to){
return $this->message->newQuery()-> create([
'content' => $content,
'from_id' => $from,
'to' => $to,
'created_at' => Carbon::now()
]);
}
}
?>
此功能中的问题
public function show (User $user) {
return view('conversations/show',[
'users'=> $this->r->getConversations($this->auth->user()->id),
'user' => $user
]) ;
在此行中更精确
'users'=> $this->r->getConversations($this->auth->user()->id)
谢谢..
答案 0 :(得分:0)
尝试改用$this->auth()->user()->id
。访问auth
的路由也应包含在web
中间件中。