jonnybarnes.uk/app/Http/Controllers/ArticlesController.php

74 lines
1.9 KiB
PHP
Raw Normal View History

2016-05-19 15:01:28 +01:00
<?php
declare(strict_types=1);
2016-05-19 15:01:28 +01:00
namespace App\Http\Controllers;
2017-12-19 16:00:42 +00:00
use App\Models\Article;
use Illuminate\Database\Eloquent\ModelNotFoundException;
2019-10-27 16:29:15 +00:00
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
2016-05-19 15:01:28 +01:00
use Jonnybarnes\IndieWeb\Numbers;
class ArticlesController extends Controller
{
/**
* Show all articles (with pagination).
*
* @param int|null $year
* @param int|null $month
2019-10-27 19:31:33 +00:00
* @return View
2016-05-19 15:01:28 +01:00
*/
public function index(int $year = null, int $month = null): View
2016-05-19 15:01:28 +01:00
{
$articles = Article::where('published', '1')
->date($year, $month)
->orderBy('updated_at', 'desc')
->simplePaginate(5);
2016-05-19 15:01:28 +01:00
return view('articles.index', compact('articles'));
2016-05-19 15:01:28 +01:00
}
/**
* Show a single article.
*
2019-10-27 19:31:33 +00:00
* @param int $year
* @param int $month
* @param string $slug
* @return RedirectResponse|View
2016-05-19 15:01:28 +01:00
*/
public function show(int $year, int $month, string $slug)
2016-05-19 15:01:28 +01:00
{
try {
$article = Article::where('titleurl', $slug)->firstOrFail();
} catch (ModelNotFoundException $exception) {
abort(404);
}
2016-05-19 15:01:28 +01:00
if ($article->updated_at->year != $year || $article->updated_at->month != $month) {
2018-01-06 21:50:15 +00:00
return redirect('/blog/'
. $article->updated_at->year
. '/' . $article->updated_at->format('m')
2019-10-27 19:31:33 +00:00
. '/' . $slug);
2016-05-19 15:01:28 +01:00
}
return view('articles.show', compact('article'));
2016-05-19 15:01:28 +01:00
}
/**
* We only have the ID, work out post title, year and month
* and redirect to it.
*
* @param string $idFromUrl
2019-10-27 19:31:33 +00:00
* @return RedirectResponse
2016-05-19 15:01:28 +01:00
*/
public function onlyIdInUrl(string $idFromUrl): RedirectResponse
2016-05-19 15:01:28 +01:00
{
$realId = resolve(Numbers::class)->b60tonum($idFromUrl);
$article = Article::findOrFail($realId);
2016-05-19 15:01:28 +01:00
return redirect($article->link);
}
}