Laravel Blade "undefined Variable" Error When Using Route()
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 target="_blank" rel="nofollow noreferrer" 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}', '[email protected]')->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 target="_blank" rel="nofollow noreferrer" 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 target="_blank" rel="nofollow noreferrer" 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?
Answer
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 target="_blank" rel="nofollow noreferrer" href="{{ route('profile', $question->user->id) }}">{{ $question->user->name }}</a>
^^^^^^^^^
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?