mercredi 26 février 2020

Handling Laravel Eager Loading between Models in Controllers

I am struggling to get my head round how to structure eager loading between Models in my controllers

To start off I have two models which have a Many to Many relationship between them:

class HelpOption extends Model
{

    ...

    public function issue()
    {
        return $this->belongsToMany(Issue::class, 'issues_help_options', 'help_option_id');
    }
}

class Issue extends Model
{

    ...

    public function helpOption()
    {
        return $this->belongsToMany(HelpOption::class, 'issues_help_options', 'issue_id');
    }

}

Both the Issue and Help Option classes are defined within their own controllers, utilising typically CRUD methods, however to define the relationship I then defined an IssueHelpOptionController. I did this so I can easily return all Issues with their associated HelpOptions, however would this have been better to define in the IssueController's index method? I primarily did this so I could still retain the ability to retrieve the Issues without eager loading the other data.

class IssueHelpOptionController extends BaseController
{

    public function index()
    {
        $issues = Issue::with('messages')->get();

        // return response
        return $this->sendResponse($issues->toArray(), 'Escalated Issues retrieved successfully.');
    }

    public function show(Issue $issue)
    {
        $issue = Issue::where('id', '=', $issue->id)->with('messages')->first();

        // return response
        return $this->sendResponse($issue->toArray(), 'Escalated Issues retrieved successfully.');
    }
}

I feel that this method makes the Routes I defined around issues-help-options very clunky and not obvious to someone else who might pickup my code:

Route::get('/issues', 'IssueController@index');
Route::get('/issues/monthly', 'IssueController@getByMonth');
Route::get('issues/{escalatedIssue}', 'IssueController@show');
Route::patch('issues/{escalatedIssue}', 'IssueController@update');
Route::post('issues/{escalatedIssue}', 'IssueController@store');
Route::delete('issues/{escalatedIssue}', 'IssueController@destroy');

Route::get('/issues-help-options', 'IssueHelpOptionController@index');
Route::get('/issues-help-options/{escalatedIssue}', 'IssueHelpOptionController@show');

I would be grateful if someone could help clarify if I am currently going the correct way, or whether I need to adjust my approach at all. I have been struggling to find a lot of up-to date documentation about how to structure these controllers.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire