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.
you are returning the relation not the actual EstadoCivil collection.
use return Pessoa::find($request->user()->pessoa_id)->estadoCivil
without parenthesis
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With