laravelundefined-variable

Undefined variable on Laravel


I´m a beginner starting with Laravel. I´m trying to show a question made on this website.

Here is the Controller page:

public function show($id)
{
    //Use the model to get 1 record from the database
    $question = $Question::findOrFail($id);

    //show the view and pass the record to the view
    return view('questions.show')->with('question', $question);
}

I have included at the top of the file:

    use App\Question;

Here is my blade page:

@section('content')

<div class="container">
    <h1> {{ $question->title }} </h1>
    <p class="lead">
        {{ $question->description }}
    </p>

    <hr />
</div>

@endsection

In the model I have not defined anything since I don´t need to specify any special rule. And finally here is the Route:

Route::resource('questions', 'QuestionController');

I got the error "ErrorException Undefined Variable: Question" and supposedly the error is on:

$question = $Question::findOrFail($id);

I´m looking forward to your observations.

Kind Regards.


Solution

  • You just need to change the controller section

    public function show($id)
    {
        //Use the model to get 1 record from the database
        $question = Question::findOrFail($id); // here is the error
    
        //show the view and pass the record to the view
        return view('questions.show')->with('question', $question);
    }
    

    Explanation:- You are going to use a variable $Question that is not defined. This is the basic PHP error, not the laravel issue. However, You are using the "App\Question" model class not a sperate variable.