Multiple tables in one model - Laravel

独自空忆成欢 提交于 2019-12-04 12:03:48
Chris Goosey

Firstly I should say each model is written for a specific table, you can't squeeze three tables into one model unless they are related. See Here

There are two ways I would go about making your code more DRY. Instead of passing your data in a chain of withs I would pass it as the second parameter in your make:

public function index() { 
    $data = array(
        'index_slider'  => IndexSlider::all(),
        'index_feature' => IndexFeature::all(),
        'footer_boxes'  => FooterBoxes::all(),
    );

    return View::make('index', $data);
}

Passing data as the second parameter. See here

The other way I would go about it, and this is a better solution if your application is going to grow large, is to create a service (another model class but not hooked up to eloquent) that when you call will return the necessary data. I would definitely do it this way if you are returning the above data in multiple views.

An example of using a service would look something like this:

<?php 
// app/models/services/indexService.php
namespace Services;

use IndexSlider;
use IndexFeature;
use FooterBoxes;

class IndexService
{
    public function indexData()
    {
        $data = array(
            'index_slider'  => IndexSlider::all(),
            'index_feature' => IndexFeature::all(),
            'footer_boxes'  => FooterBoxes::all(),
        );

        return $data;
    }
}

and your controller:

<?php
// app/controllers/IndexController.php

use Services/IndexService;

class IndexController extends BaseController
{
    public function index() { 
        return View::make('index', with(new IndexService())->indexData());
    }
}

This service can be expanded with a lot less specific methods and you should definitely change the naming (from IndexService and indexData to more specific class/method names).

If you want more information on using Services I wrote a cool article about it here

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!