Error making the list

Asked

Viewed 33 times

0

Trying to get Property of non-object:

 @foreach($civis as $civil)
                  <tr>
                    <td>01</td>
                    <td>{{$civil->matricula}}</td>
                    <td>{{$civil->nome}}</td>
                    <td>{{$civil->sub_unidade->first()->sub_unidade}} </td>
                    <td>{{$civil->cpf}}</td>
                    <td>{{$civil->situacao}} </td>
                    <td>
                      <a type="button" href="{{route('civis.edit', $civil->nome)}}" class="btn btn-success fa fa-edit" title="Editar">
                      </a>
                      <a type="button" href="detcivis.php" class="btn btn-primary fa fa-eye" title="Visualizar" >
                      </a>
                    </td>
                  </tr>
               @endforeach

Civil model:

    <?php

namespace App\Models\Painel;

use Illuminate\Database\Eloquent\Model;
use App\Models\Painel\contato;
use App\Models\Painel\sub_unidade;
use App\Models\Painel\cargo;
use App\Models\Painel\matricula;
use App\Models\Painel\curso;
use App\Models\Painel\endereco;

class civil extends Model
{
    protected $table = 'civil';
    protected $fillable = ['id', 'nome', 'cpf', 'data_nascimento', 'pai', 'mae', 'situacao', 'sexo', 'estado_civil', 'endereco_id'];
    public function contato(){

        return $this->hasOne(contato::class);
    }
    public function matricula(){

        return $this->hasOne(matricula::class);
}
    public function sub_unidade(){

        return $this->belongsToMany(sub_unidade::class, 'lotacao')->wherePivot( 'status', '=', 'atual' );
}
public function endereco(){

        return $this->belongsTo(endereco::class);
}
}

Model sub_unit:

    <?php

namespace App\Models\Painel;

use Illuminate\Database\Eloquent\Model;

class sub_unidade extends Model
{
    protected $table = 'sub_unidade';
    protected $fillable = ['sub_unidade','unidade_id','id'];
    public function civil(){

        return $this->belongsToMany(civil::class);
}
    public static function sub_unidades($id){
        return sub_unidade::where('unidade_id','=',$id)
        ->get();
    }
}

my controller:

public function index()
{

    $civis = civil::orderBy('id','ASC')->paginate(200);

    return view('sistema.civis')
        ->with('civis', $civis);


}

Looks like the mistake is on the line:

<td>{{$civil->sub_unidade->first()->sub_unidade}} </td>

1 answer

0

Add the with method in your query to bring the subunits. Example : $civis = civil::orderBy('id','ASC')->with('sub_unidade')->paginate(200);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.