As a project I am building a stackoverflow like forum. On the page on which a single question is shown I want the user to be able to click on the questioner's name and be forwarded to the respective user profile page. I am able to get the name from the database with {{ $question->user->name }}
. The problem occurs when adding the <a href=""></a>
part!
Also, the profile pages work. I can access them and the url then says for example: ../profile/1
.
This is the route in the web.php file:
Route::get('/profile/{user}', 'PageController@profile')->name('profile');
This is the PageController part:
public function profile($id)
{
$user = User::with(['questions', 'answers', 'answers.question'])->find($id);
return view('profile')->with('user', $user);
}
This is the code from the show.blade View question page which does not work:
<p>
Submitted by <a href="{{ route('profile', $user->id) }}">{{ $question->user->name }}</a>
</p>
The error message I get is Undefined variable: user
.
Which surprises me because forwarding on the profile page to a specific question works with this blade code:
<a href="{{ route('questions.show', $question->id) }}">View Question</a>
The respective route in the web.php file:
Route::resource('questions', 'QuestionController');
And QuestionController:
public function show($id)
{
$question = Question::findOrFail($id);
return view('questions.show')->with('question', $question);
}
I thought I defined the variable $user
in the PageController like I defined $question
in the QuestionController?
I can see you are using Eloquent models with relations. If you want to display the user id on the question, you can use the relation between the Question
and User
to find the id of the posting user.
Submitted by <a href="{{ route('profile', $question->user->id) }}">{{ $question->user->name }}</a>
^^^^^^^^^
//just change your like this way
public function profile($id)
{
$user = User::with(['questions', 'answers', 'answers.question'])->find($id);
return view('profile',compact('user));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.