mardi 29 novembre 2016

Trying to get property of non-object in Laravel 5

I'm getting the ErrorException: Trying to get property of non-object

I'm trying to display all the relationship that is link using this function. The relationship is ->

-Card can have many notes, Notes only have one card. -Each notes contain only one user, User contain only one card. My code is:

Model

  1. Note

    class Note extends Model { protected $fillable = ['body'];

    public function cards()
    {
        return $this->belongsTo(Card::class);
    }
    
    public function users()
    {
        return $this->belongsTo(User::class,'id');
    }
    
    

    }

  2. User

    class User extends Authenticatable { use Notifiable;

    public function note()
    {
        return $this->belongsTo(Note::class);
    }
    
    protected $fillable = [
        'name', 'email', 'password',
    ];
    
    protected $hidden = [
        'password', 'remember_token',
    ];
    
    

    }

  3. Card

    class Card extends Model { public function notes() { return $this->hasMany(Note::class);//relationship }

    public function addNote(Note $note)
    {
        return $this->notes()->save($note);
    }
    
    

    }

Controller

  1. cardsController

    class cardsController extends Controller { public function index() { $cards = Card::all(); return view('cards.index',compact('cards')); }

    public function show(Card $card)
    {
        $card->load('notes.user'); **The Error is here.**
        $return $card;
        return view('cards.show',compact('card'));
    
    
    }
    
    

    }

  2. notesController

    class notesController extends Controller {

    public function store(Request $request, Card $card)
    {
        $card->addNote(
                new Note($request->all())
            ); 
    
        return back();
    }
    
    public function edit(Note $note)
    {
        return view('notes.edit',compact('note'));
    }
    
    public function update(Request $request, Note $note)
    {
        $note -> update($request -> all());
    
        return back();
    }
    
    

    }

DB

1. notes table

$card->load('notes.user'); -when i just put (notes) in the cardControllers function, it will appear all data that link from card and notes table. -but when i try to add (notes.user) it said that trying to get non property obejct. Am i missing something?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire