mercredi 24 août 2016

Laravel - how can I have a model available across each controller

I'm working on a laravel site that where every page is composed of two parts. I guess one way to abstract it would be to consider a multi-hosted blog, with the format {url}.blog.com/{category} (we can assume that the blog is further partitioned into categories, and each post has to belong to exactly one category).

At the moment, I have a route group that handles the {url} and {category} for me, which is fine, it means I have have my routes looking like this:

Route::get('/p/{post}', 'PostController@viewPost');
Route::get('/a/{author}', 'AuthorController@viewAuthor');

My problem is though, that every single method in my controller looks something like this:

function viewPost(Request $request, $url, $category, $post)
function viewAuthor(Request $request, $url, $category, $author)

Which means that I need to pass everything into my view, like so:

return view('posts/viewSingle', [
    'title' => $post->title,
    'url' => $url,
    'category' => $category,
    'post' => $post
]);

I'm seeing that there is a lot of duplicated code here, it would be great if I could somehow remove the url and category from each of my controller methods and still have access to it (I guess in the same way I can use Auth across my app).

The problem is, that this is my first attempt at using a PHP framework, and I'm not really away of the best practices. Based on my reading, I think I need two service providers, but I have no idea as to how to set them up.

I think my issues are further complicated in that I need to access the Request object in order to determine what url and what category I need to fetch from the database.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire