jeudi 24 novembre 2016

Calling a onetoMany relationship throwing a undefined property error, why? Laravel 5.3

I'm trying to figure out how Laravel handles pivot tables. I'm sorta kinda almost there, and then this error pops up:

Undefined property: Illuminate\Database\Eloquent\Collection::$subcategory 

I'm 99% sure it's because I'm not calling the relationship properly, and as a result it can't pull out the data from the object. However, because Laravel has a very mystical way of doing pivots, and after hours of trawling through documentation, tutorials and explanations. I'm still fairly lost on how to implement the relationship. This is what I've got so far. What am I getting wrong?

The tags model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Ministry_Prefs_User extends Model
{
    protected $table = 'ministry_prefs';

   public function ministry_prefs_user() {

      return  $this->belongsToMany('App\UserEdit', 'tag_user', 'tag_id', 'user_id');
   } 
}

The relevant user model code:

public function ministry_prefs_user() {

      return  $this->belongsToMany('App\Ministry_Prefs_User', 'tag_user', 'user_id', 'tag_id');
    } 

The controller:

public function show($id)
    {
        try {
         $loc = UserEdit::findorFail($id);
         $array = UserEdit::findorFail($id)->toArray();
         //$prefs = Ministry_Prefs_User::find($id);
         return view('UserEdit', compact('array', 'loc'));

         } catch(\Exception $e) {
             return \Redirect::route('users.index')
                ->withMessage('This user does not exist');
         }


    }

The blade printing the test data:

 

Tried this, which definitely didn't work:

  @Foreach ($prefs->ministry_prefs_user as $pref)
                <br>
                : 

    @Endforeach

The tag_user table looks a bit like this with foreign keys properly linked (I think):

tag_user

The data is stored like so: tags

The table the tags reference looks a bit like this:

prefs

Yeah, I inherited this, so it's all over the place. I'm cleaning up as best I can given deadlines approaching. But I'm still learning the automation processes and I'm careful to avoid potentially breaking the data.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire