Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chagouani's avatar

table liste whith laravel

I have a teble intervention that contains date, duree_prevu, client-id, technicien_id with a relation one to mony and (technician - client) inherits their information of table user (nom, prenom, email ....)

the want to display in the index page a table which contains " nom client and nom technicien " it displays an error ("Trying to get property of non-object (View: C:\xampp\htdocs\projet\resources\views\intervention\index.blade.php)")

and when I show one of the two it shows the result of the nom

@extends('Layouts.app')
@extends('Layouts.master')
@section('content')

        <div class="col-lg-12">
            <h1 class="page-header">Intervention</h1>
        </div>
        <div class="row">
            <div class="col-lg-10">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        DataTables Advanced Tables
                        <div class="pull-right">
                            <a href="{{url('intervention/create')}}">Nouveau Intervention</a>
                        </div>
                    </div>
                    <!-- /.panel-heading -->
                    <div class="panel-body">
                        
                        <table width="100%" class="order-table table" >
                            <thead>
                            <tr>

                                <th>date_intervention <br />
                                    <input type="date" class="light-table-filter" data-table="order-table" 
          placeholder="Filter" style="width: 120px;"></th></th>
                                <th type="date">Duré Prévu <br />
                                    <input type="date" class="light-table-filter" data-table="order-table" 
          placeholder="Filter" style="width: 180px;"></th></th>
                                 <th>technicien <br />
                                    <input type="search" class="light-table-filter" data-table="order-table" 
          placeholder="Filter" style="width: 120px;"></th>
                                <th>client <br />
                                    <input type="search" class="light-table-filter" data-table="order-table" 
           placeholder="Filter" style="width: 120px;"></th>    
                                <th>Action <br /> &ensp;</th>
                            </tr>
                            </thead>
                            <tbody>
                            @foreach($intervention as $intervention)
                                <tr>

                                    <td>{{$intervention->date_intervention}}</td>
                                    <td>{{$intervention->duree_prevu}}</td>
                                    <td>{{$intervention->technicien->user->nom}}</td>
                                    <td>{{$intervention->client->user->nom}}</td>
                                    

                                    <td>
                                        <form action="{{url ('intervention/'.$intervention->id)}}" 
         method="post">
                                            {{csrf_field()}}
                                            {{method_field('DELETE')}}
                                            <a href="{{url('intervention/'.$intervention->id.'/show')}}" class="btn 
         btn-primary">Details</a>

                                            <a href="{{url('intervention/'.$intervention->id.'/edit')}}" class="btn 
        btn-default">Editer</a>
                                            <button type="submit" class="btn btn-danger">Supprimer</button>
                                        </form>

                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                        <!-- /.table-responsive -->

                    </div>
                    <!-- /.panel-body -->
                </div>
                <!-- /.panel -->
            </div>
            <!-- /.col-lg-12 -->
        </div>
        </div>
       <!-- /.row -->
    </div>
<script>(function(document) {
    'use strict';

    var LightTableFilter = (function(Arr) {

        var _input;

        function _onInputEvent(e) {
            _input = e.target;
            var tables = document.getElementsByClassName(_input.getAttribute('data-table'));
            Arr.forEach.call(tables, function(table) {
                Arr.forEach.call(table.tBodies, function(tbody) {
                    Arr.forEach.call(tbody.rows, _filter);
                });
            });
        }

        function _filter(row) {
            var text = row.textContent.toLowerCase(), val = _input.value.toLowerCase();
            row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
        }

        return {
            init: function() {
                var inputs = document.getElementsByClassName('light-table-filter');
                Arr.forEach.call(inputs, function(input) {
                    input.oninput = _onInputEvent;
                });
            }
        };
    })(Array.prototype);

    document.addEventListener('readystatechange', function() {
        if (document.readyState === 'complete') {
            LightTableFilter.init();
        }
    });

    })(document);</script>
    @endsection

model intervention :

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Intervention extends Model
{
  protected $guarded = [];
 protected $fillable = [
    
    ];
 public function avisintervention()
 {
    return $this->hasMany(AvisIntervention::class);
 }

 public function technicien()
    {
    return $this->belongsTo(technicien::class);

    }

  public function client()
    {
    return $this->belongsTo(Client::class);

 }
    public function tarificationtache()
 {
    return $this->belongsTo(tarificationtache::class);

 }
}

controller

 public function index()
 {
    
    $Listintervention=intervention::with(['technicien','client','tarificationtache'])->get();
    
    return view('intervention.index',['interventions'=>$Listintervention]);

  }
0 likes
41 replies
rin4ik's avatar

@chagouani relations like this $intervention->technicien->user->nom or $intervention->client->user->nom are often causes this kinda errors . use the optional() helper. try like below

<td>{{optional($intervention->technicien->user)->nom}}</td>
<td>{{optional($intervention->client->user)->nom}}</td>  

docs http://laravel.test/docs/5.6/helpers#method-optional

chagouani's avatar

thank you for your answer but the same problem

rin4ik's avatar

it should work @chagouani try to hard refresh the browser(ctrl+f5). why in foreach loop the same variable twice? $intervention as $interventionit should be $interventions as $intervention or $intervention as $item! it will not work with this $intervention as $intervention

jcmargentina's avatar

first , this line is bad

@foreach($intervention as $intervention)

it should have dfferent variable names, line $interventions as $intervention ... check the S in the first one.

second ... probably one of this lines are giving you a "NULL value in the middle" making the relation to fail.

<td>{{$intervention->technicien->user->nom}}</td>
<td>{{$intervention->client->user->nom}}</td>

maybe the raltion fails on the first arrow (->), or the second, ... etc. , so ... start an old school debug process ... how? just try the different relations on them like so ...

One at the time, what you want to know is wich relation is failing and where so delete one of the items, and start with the first one only, if completed, ... continue with the next one.

in some point of this, you will see the NULL or empty value that is causing the failure, ... if is not in the first it will appear in the second.

do

<td>{{$intervention->technicien}}</td>
<td>$intervention->client->user->nom </td>

then

<td>{{$intervention->technicien->user}}</td>
<td>$intervention->client->user->nom </td>

then

<td>{{$intervention->technicien->user->nom}}</td>
<td>$intervention->client->user->nom </td>

did it show up? .. no ? ok move to the second

<td>{{$intervention->technicien->user->nom}}</td>
<td>{{$intervention->client }} </td>
<td>{{$intervention->technicien->user->nom}}</td>
<td>{{$intervention->client->user}}</td>
<td>{{$intervention->technicien->user->nom}}</td>
<td>{{$intervention->client->user->nom}} </td>

did you find the one that is making your relation to fail?

PD: there are more suitable ways to handle this, but .... this will help you understand a basic and horrible debugging workaround.

chagouani's avatar

@rin4ik he always shows the same mistake whith changed $interventions as $intervention

rin4ik's avatar

@chagauni please try to clear everything from index file and see something changes? did you try these lines below ? you shouldn't see that error

<td>{{optional($intervention->technicien->user)->nom}}</td>
<td>{{optional($intervention->client->user)->nom}}</td>  
chagouani's avatar

@rin4ik where I find the index file .........................................

jcmargentina's avatar

@chagouani , ... I am totally confused, how can they work separatly and when you put them together they crash? ... WTF? LOL LOL LOL, I really want to solve this puzzle.

chagouani's avatar

@rin4ik delete all the code in the page index.blade.php and I put the code it displays this error

Property [technicien] does not exist on this collection instance. (View: C:\xampp\htdocs\projet\resources\views\intervention\index.blade.php)"

jcmargentina's avatar

@chagouani , just leave the ...

@foreach($interventions as $intervention)
                <tr>
                                    <td>{{$intervention->technicien->user->nom}}</td>
                                    <td>{{$intervention->client->user->nom}}</td>
                </tr>
 @endforeach 
chagouani's avatar

@jcmargentina 1st thing I do not know why you laugh 2nd thing you want to check I can send you a picture or a video to help you to solve this puzzle

rin4ik's avatar

what this gives you try please

@foreach($interventions as $intervention)
                <tr>
                                    <td>{{optional($intervention->technicien->user)->nom}}</td>
                                    <td>{{optional($intervention->client->user)->nom}}</td>
                </tr>
 @endforeach 
jcmargentina's avatar

come on ... dont be so sensitive, I am not laughing at you my friend, I am laughing at the problem, dont take that expression personally :D

try this ... remove everything from your view ... leave it blank .

and check it again .

maybe the problem is in the controller ... maybe.

can you provide the controller code ?

jcmargentina's avatar

can you please check this code ?

 public function index()
 {
    
    $Listintervention=intervention::with(['technicien','client','tarificationtache'])->get();
    
    return view('intervention.index',['interventions'=>$Listintervention]);

  }

should it be ...

//with capital i 
$Listintervention=Intervention::with(['technicien','client','tarificationtache'])->get();    

I assumed you added the Intervention model at the top your controller code first

rin4ik's avatar

here you should change them all. class name always should be with capital letter.

return $this->belongsTo(technicien::class);

to this

return $this->belongsTo(Technicien::class);

--

 $Listintervention=intervention::with(['technicien','client','tarificationtache'])->get();

++

 $Listintervention=Intervention::with(['technicien','client','tarificationtache'])->get();

--

    return $this->belongsTo(tarificationtache::class);

++

 return $this->belongsTo(Tarificationtache::class);
jcmargentina's avatar

so .. is not in the view ... I already sent you a fix in the controller (keep it) and stil the same ... IS THE RELATION!!!!!

specify the fields in the realtionship ...

return $this->belongsTo(technicien::class, field_origin, field_destiny);

/*
or

return $this->belongsTo(Technicien::class, field_origin, field_destiny);

depending on your code

*/

can you please show your databse tables? for Intervention and Technicien?

did you follow the convention names when you named the fields? ... just in case explicitly name them in the relation

chagouani's avatar

@rin4ik I dont know why he works each one alone and when I put them together, I dont think it's a model problem.

rin4ik's avatar

technicien and client model has this relation?

public function user(){
return $this->belongsTo(User::class)
}
chagouani's avatar

intervention table

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateInterventionsTable extends Migration
{
    /**
    * Run the migrations.
     *
    * @return void
     */
 public function up()
 {
    Schema::create('interventions', function (Blueprint $table) {
        $table->increments('id');
        $table->date('date_intervention');
        $table->string('description');
        $table->dateTime('duree_prevu');
        $table->boolean('statut');
        $table->integer('technicien_id')->unsigned();
        $table->foreign('technicien_id')->references('id')->on('techniciens');
        $table->integer('tarification_id')->unsigned();
        $table->integer('client_id')->unsigned();

        $table->timestamps();
    });
   }

    /**
     * Reverse the migrations.
     *
  * @return void
     */
 public function down()
    {
        Schema::dropIfExists('interventions');
    }   
}

technicientable

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTechniciensTable extends Migration
{
/**
         * Run the migrations.
     *
     * @return void
    */
    public function up()
  {
    Schema::create('techniciens', function (Blueprint $table) {
        $table->increments('id');
        $table->boolean('actif')->default(1);
        $table->float('moyenne_avis');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->datetime('deleted_at')->nullable();
        $table->timestamps();
        
    });
 }

 /**
    * Reverse the migrations.
     *
     * @return void
     */
 public function down()
 {
    Schema::dropIfExists('techniciens');
    $table->dropColumn('deleted_at');
 }
}

client table

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateClientsTable extends Migration
{
  /**
    * Run the migrations.
    *
    * @return void
     */
    public function up()
    {
    Schema::create('clients', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');

        $table->timestamps();
    });

  }

    /**
  * Reverse the migrations.
     *
     * @return void
  */
 public function down()
 {
    Schema::dropIfExists('clients');
  }
}
rin4ik's avatar

@chagouani this one works

                                  <td>{{$intervention->client->user->nom}}</td>

this isn't?

                       <td>{{$intervention->technicien->user->nom}}</td>
jcmargentina's avatar

edit every "belongsTo" relation in the models involved in this problem for example as this ...

 public function technicien()
    {
    return $this->belongsTo(technicien::class)->withDefault([]);

    }

see the withDefault() ??? add that to every "belongsTo" relation in the models involved and check again if we can mitigate the error ... at least

Next

Please or to participate in this conversation.