Usman Developer
Usman Developer

Reputation: 578

Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$diffi_lvl_name

I am getting error in Laravel 5.7 while creating relationship, I have created a relationship as: Question.php:

public function diffi_lvl() {
    return $this->belongsTo('App\DifficultyLevel');
}

and DifficultyLevel.php:

public function questions() {
    return $this->hasMany('App\Question');
}

after that I used:

@foreach ($questions as $question)
    {{ dd($question->diffi_lvl()->diffi_lvl_name) }}
@endforeach

and QuestionController.php:

public function index()
{
    $questions = Question::all();
    return view('questions.index', compact('questions'));
}

difficulty level migration:

public function up()
{
    Schema::create('difficulty_levels', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->string('diffi_lvl_name');
        $table->timestamps();
    });
}

and the question migration:

public function up()
{
    Schema::create('questions', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->text('question');
        $table->unsignedInteger('difficulty_level_id');
        $table->foreign('difficulty_level_id')->references('id')->on('difficulty_levels');
        $table->timestamps();
    });
}

but it's giving me this error as;

Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$diffi_lvl_name

Note: I also used this {{ dd($question->diffi_lvl->diffi_lvl_name) }} getting Trying to get property of non-object

Upvotes: 1

Views: 4345

Answers (2)

Mozammil
Mozammil

Reputation: 8750

Change your relationship as follows:

public function diffi_lvl() {
    return $this->belongsTo('App\DifficultyLevel', 'difficulty_level_id');
}

public function questions() {
    return $this->hasMany('App\Question', 'difficulty_level_id');
}

Then, the following should work:

@foreach ($questions as $question)
    {{ dd($question->diffi_lvl->diffi_lvl_name) }}
@endforeach

For more information, read the documentation on Defining Relationships.

Edit: Actually, it seems just doing the following should work:

public function diffi_lvl() {
    return $this->belongsTo('App\DifficultyLevel', 'difficulty_level_id');
}

public function questions() {
    return $this->hasMany('App\Question');
}

Upvotes: 1

Mücahit Tekin
Mücahit Tekin

Reputation: 256

You already fixed first error with using

$question->diffi_lvl->diffi_lvl_name

And for second error there are some possibilities.

  • There is no DifficultyLevel attached to your Question model
  • We have to see your table structure.Maybe you mapped wrongly your foreign keys.Is your foreign key named "difficulty_level_id" in "questions" table?

Upvotes: 1

Related Questions