Question: Laravel Relationships -Trying to get property of non-object

Question

Laravel Relationships -Trying to get property of non-object

Answers 2
Added at 2017-01-03 22:01
Tags
Question

I am coding an RP cms and I am trying to do the following. So in my MySQL database I have two tables that are important to this question.

srp_user_statistics - Holds the roleplay data for each user, it has a user_id as the primary key that links to the users table. This table also has a government_id int column to link to the id in the government_roles

srp_government_roles - Holds a list of government roles the user can have. It has the following columns: http://image.prntscr.com/image/335f9fc5f1174236a1a7bed6eb8d7d7e.png

So what am I exactly trying to achieve here? I am trying to get all of the roleplay_statistic instances that are linked to a srp_government_roles record where the government_type is a certain value, for example I am trying to code a government page and it has a panel box for each government type, and inside that panel box it shows the information of each user that has that government type.

<?php

namespace App\Database\Website\Roleplay;

use Eloquent;
use App\Database\Website\Roleplay;

class GovernmentRole extends Eloquent
{
    protected $primaryKey   = 'id';
    protected $table        = 'srp_government_roles';
    public $timestamps      = false;
    protected $fillable     = [];

    public function stats(){
       return $this->hasMany(Roleplay::class, 'government_id');
   }
}

Roleplay class:

use Eloquent;

class Roleplay extends Eloquent
{
    protected $primaryKey   = 'id';
    protected $table        = 'srp_user_statistics';
    public $timestamps      = false;
    protected $fillable     = ['user_id'];

    public function user()
    {
        return $this->belongsTo('App\Database\Website\User\Player', 'user_id', 'id');
    }

    public function government_type()
    {
        return $this->belongsTo(GovernmentRole::class, 'government_id');
    }
}

Here is the controller of my Government page:

<?php

namespace App\Http\Controllers\Frontend\User;

use Auth;
use Cache;
use Illuminate\Http\Request;
use App\Database\Website\User\Roleplay;
use App\Database\Website\Roleplay\GovernmentRole;
use App\Database\Website\Roleplay\Life\LifeEvents;

class GovernmentController
{
    public function getView()
    {
        $government_type = GovernmentRole::where('government_type', 'higher_government')->first();
        $stats = $government_type->stats;

        foreach ($stats as $stat) {
            echo $stat->user_id . '<br>';
        }

        exit();

        return view('frontend.community.government');
    }
}

This code I added just to test:

 $government_type = GovernmentRole::where('government_type', 'higher_government')->first();
            $stats = $government_type->stats;

            foreach ($stats as $stat) {
                echo $stat->user_id . '<br>';
            }

            exit();

But with the short piece of code above I have this issue:

ErrorException in GovernmentController.php line 17:
Trying to get property of non-object

When I have fixed this issue, I want to achieve something like this:

namespace App\Http\Controllers\Frontend\User;

use Auth;
use Cache;
use Illuminate\Http\Request;
use App\Database\Website\Roleplay\Life\LifeEvents;

class GovernmentController
{
    public function getView()
    {
        $higherGovernment = Cache::remember('government.higher_government', function() {
            return Roleplay::get();
        });

        $seniorGovernment = Cache::Remeber('government.senior_government', function() {
            return Roleplay::get();
        });

        $juniorGovernment = Cache::remember('government.junior_government', function () {
            return Roleplay::get();
        });

        return view('frontend.community.government', compact('higherGovernment', 'seniorGovernment', 'juniorGovernment'));
    }
}

But I would like to actually get the players in the proper types, not just getting all the roleplay statistics as shown in the code above.

Answers to

Laravel Relationships -Trying to get property of non-object

nr: #1 dodano: 2017-01-03 22:01

I could be wrong, as I'm working on Lumen, which is a little different, but first - why do you extend Eloquent instead of Model? ( e.g. use Illuminate\Database\Eloquent\Model; class Roleplay extends Model ). I saw also a problem if I used relations without explicitly adding it to the model. So in your case:

use Illuminate\Database\Eloquent\Model;

class GovernmentRole extends Model
{
    protected $primaryKey   = 'id';
    protected $table        = 'srp_government_roles';
    public $timestamps      = false;
    protected $fillable     = [];

    protected $with = [ 'stats' ];

    public function stats(){
       return $this->hasMany(Roleplay::class, 'government_id');
   }
}

You can also add the relations "with" on your query:

$government_type = GovernmentRole::where('government_type', 'higher_government')->with( 'stats' )->first();

As I said, this will work in Lumen, but I think it should also in Laravel

nr: #2 dodano: 2017-01-03 22:01

The problem is first() method returns null when query doesn't find anything. So just add check for null to your code:

If (!is_null($government_type)) {

Or one of $stat has no user_id. You should add similar check here too or set this column as not nullable.

Source Show
◀ Wstecz