Laravel bindings modifying table columns make property undefined

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

The change was from name_id to seller_id

Before watching:

$transaction->user->first_name 

Before in a Transaction Controller:

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

After and before the controller invokes 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 watching:

 $transaction->seller->first_name 

After the controller transaction:

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

After return:

 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, table users have the standard column names user_id and first_name, and table transactions (transaction controller) now have seller_id

Not sure if this affects, but in the SQL table, primary keys in both cases: auto-increment "id"

What am I doing wrong?

+5
source share
1 answer

You have a user relationship in your Transaction model, but you are trying to access it as seller in your view.

The change:

 $transaction->seller->first_name 

To:

 $transaction->user->first_name 

Or

You can also change the relationship in your model to seller . If that is what you need.

Finally:

Display data in a view only if there are records in the link.

 @if(!empty($transaction->user)) $transaction->user->first_name @else //No users @endif 
+1
source

Source: https://habr.com/ru/post/1275074/


All Articles