Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel relationships changing table columns makes undefined property

Tags:

php

mysql

laravel

So I changed the name of a column in my Laravel app and the party started..

The change was from name_id to seller_id

Before in view:

$transaction->user->first_name

Before in controller Transaction:

class Transaction extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }
 }

After and before in controller calling the view:

public function getInfoUser($name){

   $user = User::where('register_id', $name)->where('id', auth()->user()->id)->first();

   if($user){
   return view('users.user', compact('user'));
   }
}

After in view:

$transaction->seller->first_name

After in controller Transaction:

class Transaction extends Model
{
    protected $primaryKey = 'seller_id';

    public function user(){
        return $this->belongsTo('App\User');
    }
}

After returns:

Trying to get property of non-object (View: /Users/tronne/Documents/web/resources/views/users/user.blade.php) in c7128907204dffe6676c7d88cbbc47.php (line 108) 
at CompilerEngine->handleViewException(object(ErrorException), 0) in
PhpEngine.php (line 45)
at PhpEngine-evaluatePath('/Users/tronne/Documents/web/storage/framework/views/c7128907204dffe6676c7d88cbbc47.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'user' => object(User)))
in CompilerEngine.php (line 59)
at CompilerEngine-get('/Users/tronne/Documents/web/resources/views/users/user.blade.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'user' => object(User)))
in View.php (line 137)

For reference the table users has the standard column name "user_id" and "first_name" and the table transactions (transactions controller) now has "seller_id"

Not sure if it affects, but in the SQL table, the primary keys are in both cases "id" autoincrement

What I'm doing wrong?

like image 507
TrOnNe Avatar asked Nov 07 '22 11:11

TrOnNe


1 Answers

You have a user relationship in your Transaction Model but you're trying to access it as seller in your view.

Change:

$transaction->seller->first_name

To:

$transaction->user->first_name

Or

You could also change the relationship in your model to seller. If that's what you need.

Finally:

Display data in the view only if there are records in the relationship.

@if(!empty($transaction->user))
        $transaction->user->first_name
@else
        //No users
@endif
like image 51
Sapnesh Naik Avatar answered Nov 15 '22 06:11

Sapnesh Naik