Search code examples
phplaravelcodeigniter-2

How to write this statement in Laravel model class


How do i write such a statement in Laravel Model class

SELECT * from video where view=(select max(view) from video)

$query = DB::table('video')->select('*');

$alldetails = $query->addSelect('max(view)')->get();

I intend selecting all the attribute of the video with the maximum amount of views

My Model

class Video extends Eloquent implements UserInterface, RemindableInterface {
    protected $table = 'video';

    public static function feature(){
        $query = DB::table('video')->select('*');
        $alldetails = $query->addSelect('max(view)')->get();
        return $alldetails;
    }
}

My Controller

class HomeController extends BaseController {
    public function home(){
        $feature=View::feature();

        return View::make('frontend/index')
        ->with("title","Kromatik Multimedia")
        ->with('feature'.$feature);
    }
}

My View

@foreach($feature as $fet)
    $fet->title;
@endforeach

Solution

  • Create a model like this:

    class Video extends Eloquent {
    
        // Laravel expects the table name "videos"
        // for Video model so need to specify here
        // because you didn't follow that convention
    
        protected $table = 'video';
    
    }
    

    From your controller call something like this:

    class HomeController extends BaseController {
    
        public function home()
        {
            // Get the Video model with maximum views; assumed that,
            // view field contains numeric number, i.e. 2 (two views)
            $featured = Video::orderBy('view', 'desc')->first();
    
            // Load the "index.blade.php" view from "views/frontend" folder
            return View::make('frontend.index')->with('video', $featured);
        }
    }
    

    In the view (No need to loop because only one model is passed):

    {{ $video->title }}
    {{ $video->genre }}