Last active
November 15, 2017 08:24
-
-
Save paulund/98b71d1f0a2dd670fbeeba2871d5376a to your computer and use it in GitHub Desktop.
Tutorial on how to use can be used https://paulund.co.uk/creating-view-classes-in-laravel. A gist to demo how to implement view objects in Laravel. Return this object from your controllers and you can remove duplicate return view code from your multiple controllers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use App\Http\Resources\PostIndexResource; | |
use Dappa\Blog\Repositories\PostRepository; | |
/** | |
* Homepage controller | |
*/ | |
class HomeController extends Controller | |
{ | |
/** | |
* HomeController constructor. | |
* | |
* @param PostRepository $repository | |
*/ | |
public function __construct(PostRepository $repository) | |
{ | |
$this->repository = $repository; | |
} | |
/** | |
* @return PostIndexResource | |
*/ | |
public function index() | |
{ | |
$posts = $this->repository->filter([ | |
'include' => 'tags', | |
'order_by' => '-published_at', | |
'page' => request('page') | |
]); | |
return new PostListResource($posts); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Resources; | |
use Illuminate\Contracts\Pagination\LengthAwarePaginator; | |
use Illuminate\Contracts\Support\Responsable; | |
/** | |
* Class PostListResource | |
* @package App\Http | |
*/ | |
class PostListResource implements Responsable | |
{ | |
/** | |
* @var LengthAwarePaginator | |
*/ | |
private $posts; | |
/** | |
* PostListResource constructor. | |
* @param LengthAwarePaginator $posts | |
*/ | |
public function __construct(LengthAwarePaginator $posts) | |
{ | |
$this->posts = $posts; | |
} | |
/** | |
* Create an HTTP response that represents the object. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @return \Illuminate\Http\Response | |
*/ | |
public function toResponse($request) | |
{ | |
return view('blog.post.list', [ | |
'posts' => $this->posts | |
]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment