Why do I get this error - Trying to get property of non-object

Posted 1 year ago by tundeogunde

I use Laravel 5.4

While displaying a particular view I keep getting the Error – “Trying to get property of non-object (View: C:\xampp\htdocs\enrolpad-lar\resources\views\enrolment\test.blade.php)”

Here’s a snippet of my view

@extends('layout.organizer_title_master')
@section('body')
    <div id="main-content">
        <div class="box-outer container">
            <div class="row">
                    <div id="messageAlert" class="col-md-12 alert alert-success text-center" role="alert" style="display: none;"></div>
                    <div class="col-md-4 page-container animate-box">
                        
                   </div>
                                    
                   <div class="col-md-8 page-container animate-box">
                        
                        <div class="white-container contact-box">
                            
                            @foreach ($enrolments as $enrolment)
                                <div class="row">                                   
                                    {{$enrolment->enrollee->surname}}<br>{{$enrolment->event->title}}
                                </div><hr>
                            @endforeach
                        </div>                      
                   </div>
            </div>
        </div>
    </div>    
@endsection

Here’s my Enrolment Model which is related to Enrollee and Event Models

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;


class Enrolment extends Model
{
    //
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'reference', 'enrollee_id', 'event_id', 'payment_id','status',
    ];

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];    

    /**
        Check if Enrollee has previously enrolled for this event 
    */
    public static function if_previuosly_enrolled($enrollee_id, $event_id) 
    {
        $matchThese = ['enrollee_id' => $enrollee_id, 'event_id' => $event_id];
        
        if ($enrolment = Enrolment::where($matchThese)->count()) {
            return $enrolment >= 0;
        } else {
            return false;
        }
    }

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

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

    public function payment()
    {
        return $this->belongsTo(Payment::class)->withDefault();
    }
  

    public static function saveEnrolment($enrolmentdetail)
    {
        $reference = str_random(12);
        $status = '1';
        $enrolment = enrolment::create([
            'reference' => $reference,
            'enrollee_id' => $enrolmentdetail['enrollee_id'],
            'event_id' => $enrolmentdetail['event_id'], 
            'payment_id' => $enrolmentdetail['payment_id'], 
            'status' => $status,
        ]); 
        return $enrolment;
    }    
}

Here’s my Enrollee Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Enrollee extends Model
{
    use SoftDeletes;

    //
    protected $fillable = ['firstname', 'othernames', 'surname', 'email', 'mobile', 'country_id', 'event_updates', 'refer_points'];

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at']; 
    

    /**
        Define the Many-To-Many Relationship with Interests
    */
    public function interests()
    {
        // 
        return $this->belongsToMany(Interest::class);
    }


    /**
     * Define the One-To-Many inverse relationship with Country. Get the country to which Enrollee belongs.
     */
    public function country()
    {
        return $this->belongsTo(Country::class);
    }

    public function enrolments()
    {
        return $this->hasMany(Enrolment::class);
    }

    /**
     * Get all of the enrollee's payments.
     */
    public function payments()
    {
        return $this->morphMany('App\Payment', 'payertable');
    }

    /*** Mutator functions to ensure that the name fields of the Enrollee are Capitalized */
    public function setFirstnameAttribute($value)
    {
        return $this->attributes['firstname'] = strtoupper($value);
    }

    public function setOthernamesAttribute($value)
    {
        return $this->attributes['othernames'] = strtoupper($value);
    }

    public function setSurnameAttribute($value)
    {
        return $this->attributes['surname'] = strtoupper($value);
    }
    /*** End Capitalize Enrollee names */

    
}

And my Event Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\SoftDeletes;

class Event extends Model
{
    use SoftDeletes;

    /**
     * Define the One-To-Many inverse relationships
     */
    public function organizer()
    {
        return $this->belongsTo(Organizer::class);
    }

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

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

    public function enrolments()
    {
        return $this->hasMany(Enrolment::class);
    }

    public function payouts()
    {
        return $this->hasMany(Payout::class);
    }

    /**
     * Get all of the event's payments.
     */
    public function payments()
    {
        return $this->morphMany('App\Payment', 'paymenttable');
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'description', 'event_date', 'end_date','duration', 'organizer_id', 'venue', 'country_id', 'allowed_enrollees', 'status', 'fee','interest_id',  'poster','online_payment','private_event', 'private_key',
    ];

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];
}

The Snippet from the enrolmentController that calls the view

public function showenrolments($event_id)
    {
        //
        $user = Auth::user();
        $event = Event::find($event_id);

        if ($user->id == $event->organizer_id) {            
            $enrolments = Enrolment::where('event_id', '=', $event_id)->get(); // Get all Enrolments for the event_id          
 
            return view('enrolment.test', compact('enrolments','event'));
        } else {
            Session::flash('danger-status','You do not have access to this event.');
            return redirect('organizer/myevents');
        }
    }

Here’s what I’ve tried

  • For each enrolment in the view, if I exclude the Event object, I still get an error.
  • For each enrolment in the view, if I delete the Enrollee object and leave the Event object, I get the expected output without errors.
  • If I replace the enrollee object in the view with $enrolment->enrollee->id I get the ids of each enrollee displayed without errors.
  • If I use $enrolment->enrollee I get the only one full record of the enrollee
  • If I dd() the $enrolments in my enrolmentController, it outputs all enrolment records including the enrollee_id for each record.
  • I realize that I can view a page that shows the details of each enrolment including the details of the enrollee ….. meaning the relationship is well defined. I also displayed {{$enrolment->enrollee->surname}} to get this and it worked fine.

What could be the problem? What have I done wrong? Why am I getting this error? I’d appreciate your help.

Please sign in or create an account to participate in this conversation.