简体   繁体   中英

Laravel 5.4 relationship beLongsToMany

Hi i need fix returning view. I made relation and its returning array. How i can change this and i am not sure i made good function to relationship. I just trying lerning it i saw many tutorials and i know in Laravel is so kind magic tips to returning. My function must showing events what user was joining. I think i make it but its returning array and when i try do something like that

 @foreach($zapisevents as $zapisevent) <table class="table"> <th>{{$zapisevent->eventsave->name}}</th> </table> @endforeach 

i got error: Property [name] does not exist on this collection instance. (View: /home/mariusz/Pulpit/www/szpital/resources/views/profil/profil.blade.php)

but when i use <th>{{$zapisevent->eventsave}}</th> its returning array.

There is function for joining to event

  public function index() { $userid = Auth::user(); $zapisevents = User::with('eventsave')->where('id',(Auth::user()->id))->get(); return view('profil.profil', ['userid' => $userid], ['zapisevents' => $zapisevents]); } 
Model User:

  public function eventsave() { return $this->belongsToMany(HomeModel::class,'save_events','users_id','events_id')->withTimestamps(); } 

Model HomeModel <<<

  public function usersave() { return $this->belongsToMany(User::class,'save_events','events_id','users_id'); } 
Its returning:

[{"id":5,"name":"asdasdsa","title":"Wydzial 1","start":"2017-04-04 03:00:00","end":"2017-04-04 07:59:00","created_at":"2017-04-01 18:50:40","updated_at":"2017-04-01 18:50:40","pivot":{"users_id":3,"events_id":5,"created_at":"2017-04-01 18:50:58","updated_at":"2017-04-01 18:50:58"}},{"id":7,"name":"kkkkkkkkkkkkkkkkkkkkkkkk","title":"Wydzial 4","start":"2017-04-01 00:00:00","end":"2017-04-01 23:59:59","created_at":"2017-04-01 19:54:24","updated_at":"2017-04-01 19:54:24","pivot":{"users_id":3,"events_id":7,"created_at":"2017-04-01 19:55:41","updated_at":"2017-04-01 19:55:41"}}]

the

@foreach($zapisevents as $zapisevent)
  <table class="table">
  <th>{{$zapisevent->eventsave->name}}</th>
  </table>
  @endforeach

Should ne

@foreach($zapisevents as $zapisevent)
  <table class="table">
 @foreach($zapisevent->eventsave as $eventSave)
  <th>{{$eventsave->name}}</th>
@endForeach
  </table>
  @endforeach

in you code the name property is being called in a collection of HomeModel but it needs to be called in a model itself

When using arrays, you need to access their properties via their index like this:

$zapisevent->eventsave['name']

as opposed to:

$zapisevent->eventsave->name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM