1
votes
// models:
class Hometype extends Eloquent {
    public function development() {
        return $this->belongsTo('Development');
    }
}

class Development extends Eloquent {
    public function hometypes() {
        return $this->hasMany('Hometype', 'dev_id');
    }
}

with that, I can do:

// controller:
$development = Development::where('stuff')->first();
// view:
@foreach ($development->hometypes as $hometype)
    {{ $hometype->stuff }}
@endforeach

which is perfectly lovely.

but I can't seem to do:

// controller:
$hometype = Hometype::where('stuff')->first();
// view:
{{ $hometype->development->stuff }} // <- fails

How do I access a field on the parent Development model from within $hometype?

I'm resorting to:

'development' => Development::find($hometype->dev_id),

which seems silly.

Possible duplicate of: Laravel 4 - Can't retrieve data in a one-to-many relationship, but I'm not camelCasing...

Also similar to: Laravel 4 hasOne / belongsTo relationship (no answers here)

2

2 Answers

3
votes

As I can see, there might be two problems:

  1. The foreign key in Hometype is wrong (if you're using a different column name than "column"_id then you have to specify it)
  2. You might be fetching a Hometype record whose development row doesn't exist
0
votes

Accessing data and methods between hasMany and belongsTo First get required models and then loop through

These are the model:

class ExpenseCategory extends Model
  public function expense_transactions()
  {
      return $this->hasMany('App\ExpenseTransaction');
  }


  class ExpenseTransaction extends Model
      public function expense_category()
      {  
          return $this->belongsTo('App\ExpenseCategory');
      }

Schema for the above model:

Schema::create('expense_transactions', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('expense_category_id')->nullable();
    $table->unsignedInteger('day_sheet_id')->nullable();
    $table->string('expense_title')->nullable();
    $table->unsignedInteger('amount');
    $table->timestamps();

$table->foreign('expense_category_id')
      ->references('id')->on('expense_categories')
      ->onDelete('cascade');

$table->foreign('day_sheet_id')
      ->references('id')->on('day_sheets')
      ->onDelete('cascade');

Schema for category:

Schema::create('expense_categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();  
    });

find only expense transactions for day sheet id in model

$expenseTransactions = ExpenseTransaction::where('day_sheet_id', $id)->get();

show their category name access in blade: in a foreach loop

@foreach($expense_transactions as $expense_transaction)
{{ $expense_transaction->expense_category->name  }}