Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent relationship returning can't convert to string

I'm trying to map an existing one to one relationship in my database using Eloquent following the Laravel tutorial and I'm receiving a string conversion error.

I have to use an existing database that is used by other program, so I can't change the database structure.

This are my models:

Pessoa.php

 namespace App\Models;

 use Illuminate\Support\Facades\Log; use
 Illuminate\Database\Eloquent\Model;

 class Pessoa extends Model {
     protected $table = 'pessoas';
     public function estadoCivil(){
         //return EstadoCivil::find($this->estado_civil_id);
         return $this->hasOne('App\Models\EstadoCivil', 'estado_civil_id');
     } 
 }

EstadoCivil.php namespace App\Models;

 use Illuminate\Database\Eloquent\Model;
 class EstadoCivil extends Model
 {
     protected $table = 'estados_civis';
 }

I don't know what to do, but I am getting this error:

Object of class Illuminate\Database\Eloquent\Relations\HasOne could not be converted to string

I searched for typos and other mistakes and couldn't find anything. I'm not even trying to convert anything to string to get this error, the types in the database for the id and the foreign key are the same too.

Here is the controller that is using it:

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Pessoa as Pessoa;

class Eu extends Controller
{
    public function __construct()
    {
    }

    public function dadosCompletos(Request $request){
        return Pessoa::find($request->user()->pessoa_id)->estadoCivil();
    }
}

If I just use return Pessoa::find($request->user()->pessoa_id) it works fine and returns the data correctly from pessoas table.

like image 770
Gustavo Magalhães Avatar asked Mar 06 '23 01:03

Gustavo Magalhães


1 Answers

you are returning the relation not the actual EstadoCivil collection. use return Pessoa::find($request->user()->pessoa_id)->estadoCivil without parenthesis

like image 74
Masoud Haghbin Avatar answered Apr 28 '23 07:04

Masoud Haghbin