Created
March 26, 2018 13:35
-
-
Save martinbean/453ac1dbedeebdf2da71e0fe13fd4ac6 to your computer and use it in GitHub Desktop.
Using Laravel’s Responsable interface to create view models
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\Article; | |
use App\Http\Views\ArticleIndex; | |
class ArticleController extends Controller | |
{ | |
public function index() | |
{ | |
$articles = Article::latest()->paginate(); | |
return new ArticleIndex($articles); | |
} | |
} |
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\Views; | |
use App\Http\Resources\ArticleResource; | |
use Illuminate\Contracts\Support\Responsable; | |
use Illuminate\Database\Eloquent\Collection; | |
class ArticleIndex implements Responsable | |
{ | |
private $articles; | |
public function __construct(Collection $articles) | |
{ | |
$this->articles = $articles; | |
} | |
public function toResponse($request) | |
{ | |
if ($request->wantsJson()) { | |
return ArticleResource::collection($articles); | |
} elseif ($request->wantsRss()) { | |
return view('article.rss', compact('articles')); | |
} else { | |
return view('article.index', compact('articles')); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment