3
\$\begingroup\$

I'm a clean guy when I code and I don't like typing the same thing over and over again, so I will try to be simple.

In my Laravel project I have two routes for every major page on the website, for example:

Route::get('/artigos','GlobalController@gestorArtigos');
Route::get('/artigos/{id}','GlobalController@gestorArtigos');

When it receives an ID in the controller:

 public function gestorArtigos(Request $request , $id = '') {
    $MyOutput = view('artigos.art_gestor_base');
    if($id){
        return $MyOutput->with('id',$id);
    }
    return $MyOutput->with('request',$request);
}

This is completely fine and I have no intention of changing this. What does bother me is the fact that I have to repeat the same function every single time I create a new page. The only differences are the function name and the value of $MyOutput, because the views change.

I need help to compact the function to a 'global' one so I don't have to repeat the code, just call it.

\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

I don't think you need to pass $request to the view, because you can access it anyway with Laravel's helper request() function.

For the routes you can use optional parameters, something like.

Route::get('/artigos/{id?}','GlobalController@gestorArtigos');

For the views and repetitive checks you can always use view composers or middlewares depends on the case really.

Eventually you could create trait with function to perform this repetitive task and include it in controller, for instance:

trait RepetitiveTask
{
    public function fireView($output, $id)
    {
        return ($id) ? $output->with('id', $id) : $output;
    } 
}

class YourController 
{
    use RepetitiveTask;

    public function gestorArtigos(Request $request) 
    {
        return $this->fireView(view('artigos.art_gestor_base'), $request->id);
    }
}

However i would use middlewares or view composers instead.

Whatever you do, make sure you keep the logic out of the views.

\$\endgroup\$
1
  • \$\begingroup\$ Wow, works like a charm, thank you very much, so compact now! \$\endgroup\$ Commented Oct 6, 2017 at 9:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.