-2

I, ve got problem with eloquent relationships. This is my DB

https://i.stack.imgur.com/2we4g.jpg https://i.stack.imgur.com/20KeG.jpg

I've got Santander ID in santander column in partner table and want to use data from those two table like from one

This is my Partner.php model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Partner extends Model
{
    use HasFactory;



    protected $table='partner';
    protected $connection='mysql2';

    protected $guarded = [];


    public $primaryKey = 'id';


    public function santander()
    {
        return $this->hasOne(Santander::class, 'id', 'santander');
    }


}

This is my Santander.php model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Santander extends Model
{
    use HasFactory;



    protected $table='santander';
    protected $connection='mysql2';

    protected $guarded = [];

   
    public $primaryKey = 'id';



    public function partner()
    {
        return $this->belongsTo(Partner::class, 'id', 'santander');
    }

}

In controller I use Eloquent collection like this:

 use App\Models\Partner;
 use App\Models\Santander;

 $partners = Partner::paginate(10);

In view. I am using it like this:

@foreach partners as partner
    {{  $partner->santander->operator }}
@endforeach

but it generates error:

Trying to get property 'santander' of non-object

Piotrexed
  • 3
  • 3

1 Answers1

1

First of all are you sure about the relationships itself?
$this->hasOne(Santander::class, 'id', 'santander');

The first extra argument should be the foreign key, so assuming that the related column in the model Santander is named santander then it should be:
$this->hasOne(Santander::class, 'santander', 'id');
(the specified id as last param can be omitted btw)

Same goes for the relationship in the other model.

deerdama
  • 11
  • 1
  • Thank You for your try but I changed this and it didn't helped. Have now same error: Trying to get property 'operator' of non-object – Piotrexed Mar 22 '21 at 20:18