mercredi 30 septembre 2015

Undefined property: stdClass::$**** in One to Many Relationships Laravel 5

I am new to Laravel and I am creating a Laravel5 project where the Voters is related to a City in one to many relationships: every voter has only one City while City has many voters

My Table looks like this

//voters

Id Name City_id

//city

Id Name 

And inside App/Models

//city.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
/**
*The table associated with the model
*
*/
protected $table = 'city';

/**
* indicates if the model should be timestamped
* @var bool
*/

public $timestamps = false;

 public function voters()
 {
    return $this->belongsTo('App\models\Voters');
 }
}

voters.php

 <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Voters extends Model
{
 protected $table = 'voters';

 public function city()
 {
    return $this->hasMany('App\Models\City');
 }
}

I can accessed all voters in the controller this way

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class VotersController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
  public function index()
  {
     $voters = DB::table('voters')->get();
     return view('voters.all_voters',['voters' => $voters] );
  }
 }

But the problem is the voter's city return an error

Undefined property: stdClass::$city (View: .....

The blade template

<div class="table-responsive">
<table class="table table-hover table-bordered table-condensed">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Profession</th>
            <th>City</th>
            <th>Province</th>
            <th>Region</th>
            <th>Island</th>
        </tr>
    </thead>
    <tbody>
        @foreach($voters as $voter)
        <tr>
            <td>{{ $voter->firstname }}</td>
            <td>{{ $voter->birthday }}</td>
            <td>{{ $voter->profession_id }}</td>
            <td>{{ $voter->city->name }}</td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        @endforeach
    </tbody>
</table>

How to properly display related field for this kind of relationships in Laravel?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LRameC
via IFTTT

Aucun commentaire:

Enregistrer un commentaire