Search code examples
arrayslaravel-5has-many

Displaying array values in laravel 5.2


I have the following hasMany() relationship in App\User.php ,

public function partner_preference_occupation()
{
    return $this-hasMany('App\Models\User\PartnerPreferenceOccupation', 'user_id');

}

The following is my PartnerPreferenceOccupation Model,

<?php

namespace App\Models\User;

use App\Models\BaseModel,
App\Models\ValidationTrait;

class PartnerPreferenceOccupation extends BaseModel {

use ValidationTrait;

public function __construct() {
    parent::__construct();

    $this->__validationConstruct();
}

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'partner_preferences_occupation';  

protected $fillable = array('user_id', 'occupation_id');
protected $dates = array();
public $uploadPath = array();

protected function setRules() {

    $this->val_rules = array();
}

protected function setAttributes() {

    $this->val_attributes = array();
}

public function occupation_name() {
    return $this->belongsTo('App\Models\Master\OccupationModel', 'occupation_id');
    }

}

I want to display the array of occupation name in my view. I tried the following code, but it fails.

{{$obj->partner_preference_occupation ? $obj-partner_preference_occupation->occupation_name->name : null}}

The error is as follows,

Undefined property:Illuminate\Database\Eloquent\Collection::$occupation_name

How can I display them.Thanks in advance.


Solution

  • Ok I got it, As it is an array of values to be fetched, I used foreach to display them in my view as,

    @if($occ=$obj->partner_preference_occupation->lists('occupation_name'))
    @foreach($occ as $oc)
    {{$oc->name}}
    @endforeach
    @endif
    

    occupatoin_name is the name of my relationship that I used in my model. And that worked for me :)