Danger Zone
Danger Zone

Reputation: 59

How to use laravel custom model functions?

I have two Models with relationship for video categories and videos

VideoCats
id | name

Videos
id | name | cat_id

I want to create a function in Model that would display number of videos according to the categories existing in the VideoCat table.

This is my Model VideoCat.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class VideoCat extends Model
{
    public function video()
    {
        return($this->hasMany('App\Video'));
    }

    public function lastfour($id)
    {
        self::with('videos')->where('name', $id)->take(5)->get();
    }    
}

and this the View where I want to display videos according to their categories

<div class="row">
  <div class="col-lg-6 col-sm-12" style="position: relative">
    @foreach ($cats as $cat)
    <div>
      <h5>{{$cat->name}}</h5>
    </div>
    <div style="position: relative;margin-bottom: 20px;">
      @foreach ($cat->videos) as $video)
      <div style="position: absolute; width: 100%; height: 100%; background: black; opacity: .5; top: 0; left:0"> 
      </div>

      <a href="/bandvideos/{{ $video->id}}">
        <img width="100%; margin-top: 15px; border-radius: 6px;"  
             src="https://img.youtube.com/vi/{{ $video->youtube_id}}/maxresdefault.jpg" alt="">
        <img src="/photos/play.png" 
             style="position:absolute; top:36%; left:42%; height:30%; width:18%" alt="" />
      </a> 
      @endforeach
    </div>
    @endforeach
  </div>
</div>

Upvotes: 0

Views: 911

Answers (1)

Kenny Horna
Kenny Horna

Reputation: 14241

Your models aren't very clear, but is this is correct: (VideoCat has many Video), then this should do the trick:

namespace App;

use Illuminate\Database\Eloquent\Model;

class VideoCat extends Model
{
    public function videos()
    {  //           ^^^^^^ [1]
        return $this->hasMany('App\Video', 'cat_id');
    }  //                                  ^^^^^^^^ Specifying the foreign key. [2]

    public function lastfour($id)
    {
        self::with('videos')->where('name', $id)->take(5)->get();
    }

}

Notes

1 - You have a one-to-many relationship, so it makes more sense to rename the relationship from video to videos (a VideoCat has many Videos)

2 - Given that your parent model is called VideoCat, Laravel will look up for a field named video_cat_id in your videos table instead of the cat_id that you want to use. In order to address this, you need to specify a custom foreign key when declaring the relationship. Check this section of the documentation.

Upvotes: 1

Related Questions