I have in the database a table of people who are assigned the id of the city they are in, like this:
In the Person model I establish the relationship between the person and their city:
class Persona extends Model
{
public function ciudad() {
return $this->belongsTo(Ciudad::class, 'ciudad');
}
}
In the controller I make a query of all the people with the list of cities :
class PersonaController extends Controller
{
public function index()
{
$personas = Persona::with('ciudad')->orderBy('id')->get();
}
}
When I do a dd($personas)
in the controller, I check that the relationship is correctly established:
There we can see that the user belongs to the city of Puerto Vallarta (returned by the id 918
present in the Persons table). Well, in the view I iterate over all the people obtaining their data, including the city:
@foreach($personas as $persona)
<tr>
[...]
<td>{{ $almacen->ciudad }}</td>
[...]
</tr>
@endforeach
This is how it looks...
Using $persona->ciudad
returns only the ID.
If I use it $persona->ciudad()->nombre
returns error (" Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name ").
If I use $persona->ciudad->nombre
it returns error (" Trying to get property 'name' of non-object ").
How do I get the names of the cities?
You must not use a name for a relation that is already the name of a column, otherwise you will always receive the value of the column, change one of them, the easiest here is the name of the relation:
Then you will get the related city like this:
Or one of its attributes:
NOTE: But if you want to follow the conventions, you should replace the column name with
ciudad_id
, so the relation would be:And you will get the related city like this:
Or one of its attributes:
BONUS: How to change the name of the column.
Create a migration:
And in the migration:
Run the migration: