Leonardo Santos
Leonardo Santos

Reputation: 300

Getting data from foreign key on view (Laravel 5.6)

I already searched for answers but I couldn't find any answer that could solve my problem.

I have 2 tables: phones and phone_types. The first one has a foreign key associated with the phone_types primary key. I want to show on view the name of phone_type through phone object. Something like $phone->phone_type->name.

My code generates this error: Trying to get property of non-object (View: /home/ablono/dev/MisServices/resources/views/painel/phones/home.blade.php)

My code is listed below.

phone_types miration table:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePhoneTypesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('phone_types', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 20);
            $table->string('description', 30);
            $table->timestamps();
        });
    }
/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('phone_types');
}

} ```

phones migration table:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePhonesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('phones', function (Blueprint $table) {
            $table->increments('id');
            $table->string('ddd')->default('13');
            $table->string('number', 20);
            $table->integer('phone_type_id')->unsigned();
            $table->foreign('phone_type_id')
                ->references('id')
                ->on('phone_types')
                ->onDelete('cascade');
            $table->timestamps();
        });

        Schema::create('phone_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('phone_id')->unsigned();
            $table->integer('user_id')->unsigned();

            $table->foreign('phone_id')
                ->references('id')
                ->on('phones')
                ->onDelete('cascade');

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('phone_user');
        Schema::dropIfExists('phones');
    }
}

I didn't code anything on PhoneType model, but here is the code:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class PhoneType extends Model
{
    //
}

Phone model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    public function users()
    {
        return $this->belongsToMany(\App\User::class);
    }

    public function phoneType()
    {
        return $this->hasMany(\App\PhoneType::class);
    }
}

Method that is sending that to view:

public function index()
    {
        $phones = Phone::all();

        return view('painel.phones.home', compact('phones'));
    }

Part of view that is listing data:

<table class="table">
            <thead>
                <th>ID</th>
                <th>DDD</th>
                <th>Número</th>
                <th>Tipo de Telefone</th>
                <th width="150px">Ações</th>
            </thead>
            <tbody>
                @foreach($phones as $phone)
                    <tr>
                        <div class="loading"></div>
                        <td>{{ $phone->id }}</td>
                        <td>{{ $phone->ddd }}</td>
                        <td>{{ $phone->number }}</td>
                        <td>{{ $phone->phone_type_id->name }}</td>

                        <td>
                            <a href="/admin/phone/users/{{ $phone->id }}"><i class="fa fa-lg fa-phone" title="Visualizar usuários que usam {{ $phone->number }}"></i></a>
                            <a href="/admin/phone/edit/{{ $phone->id }}"><i class="fa fa-lg fa-pencil" title="Editar {{ $phone->number }}"></i></a>
                            <a href="/admin/phone/delete/{{ $phone->id }}"><i class="fa fa-lg fa-times" title="Excluir {{ $phone->number }}"></i></a>
                            <a href="/admin/phone/view/{{ $phone->id }}"><i class="fa fa-lg fa-eye" title="Visualizar {{ $phone->number }}"></i></a>
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>

Upvotes: 2

Views: 6289

Answers (2)

divya_kanak
divya_kanak

Reputation: 142

Please check your eloquent model relationship. And accessing the eloquent property is like . $main-model->$sub-model(method name of model which you want access)->property Note: When you access method please convert method name in to snake case

Upvotes: 0

Sohel0415
Sohel0415

Reputation: 9853

Change your relationship to belongsTo():

public function phoneType()
{
    return $this->belongsTo(\App\PhoneType::class, 'phone_type_id');
}

And in view

 <td>{{ $phone->phone_type->name }}</td>

Upvotes: 3

Related Questions