Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

can't access model in relations laravel

i have a problem with my models, i am trying to access model properties to recall them in blade.
the problem is that i can’t log in

this is my model Order:

<?php

namespace App\Models;

use App\Models\Restaurant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Order extends Model
{
    use HasFactory;

    protected $fillable=[
        'id_user',
        'id_wine',
        'quantita',
        'prezzo',
        'data_ordine',
        'id_restaurant',
        'pagato',
        'evaso',
    ];

    public function Restaurant(){
        return $this->belongsTo(Restaurant::class);
    }
}

and this is my model Restaurant:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?php

namespace App\Models;

use App\Models\User;
use App\Models\Order;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Restaurant extends Model
{
    use HasFactory;

    protected $fillable = [
        'ragione_sociale',
        'indirizzo',
        'citta',
        'provincia',
        'cap',
        'partita_iva',
    ];

    public function users(){
        $this->hasMany(User::class);
    }

    public function Order(){
        return $this->hasMany(Order::class);
    }
}

in blade I need to have access to the restaurant model in order to view the "ragione_sociale", but I get this error:

ErrorException
Trying to get property 'ragione_sociale' of non-object (View: C:\Users\danil\OneDrive\Desktop\progetti_kemedia\Enoteca_Etna2\resources\views\ordini\ordini.blade.php)

this is my blade view:

@foreach ($orders as $order)
        <div>
           <span>Ristorante: {{$order->Restaurant->ragione_sociale}}</span>
        </div>
@endforeach

>Solution :

change this:

public function Restaurant(){
    return $this->belongsTo(Restaurant::class);
}

to this;

public function Restaurant(){
    return $this->belongsTo(Restaurant::class, 'id_restaurant');
}

and similar,

public function Order(){
    return $this->belongsTo(Order::class);
}

to;

***(hasMany)

public function Order(){
    return $this->hasMany(Order::class, 'id_restaurant');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading