Laravel投稿サイト構築.88 -お題機能 管理画面-
前置き
前回調整周りの作業を行った。
今回からいよいよ音声機能へーと予告していたのだが、
もう1機能追加したい。
それがはてなブログにもある「お題」機能。
サイトに何か書き込んでと言われても、おおまかなお題がないと、
書き込んでもらいにくいのではないかと思い、お題機能を追加することにする。
目次
【お題】機能概要
- 画面上部に、お題一覧を表示する。
- お題は「お題」と「カテゴリ」、有効期限からなる。
- お題用テーブルを追加。テーブル名は「themes」とする。
- お題の管理はダッシュボード画面で行う。
テーブル作成
まずは箱を作ってしまう。
テーブル名はthemes
項目は「お題」「カテゴリ」「有効期限」
お題は期間限定としたいので有効期限を保持する。それを過ぎたら画面上部に表示させない。
-----
php artisan make:migration themes
-----
Schema::create('themes', function (Blueprint $table) {
$table->id()->autoIncrement();
$table->string('theme');
$table->string('category');
$table->timestamp('expiry');
$table->timestamps();
});
-----
php artisan migrate
Model作成
-----
-----
protected $fillable = [
'theme'
'category',
'expiry',
];
-----
お題の一覧を取得する関数
public function get_themes()
{
$themes = Theme::select([
't.id as theme_id',
't.theme',
't.category',
't.expiry',
])->from('themes as t')
->orderBy('t.created_at', 'desc')
->get();
return $themes;
}
-----
Controller作成
-----
php artisan make:controller ThemeController
-----
//お題の一覧を取得する関数
public function index(Request $request)
{
$dt_expire = Carbon::parse( Carbon::now()->addMonth() )->format('Y-m-d\TH:i');
$md_theme = new Theme();
$themes = $md_theme->get_themes();
return view('dashboard', compact('dt_expire', 'themes'));
}
-----
// お題を登録する関数
public function store_theme(Request $request)
{
$md_theme = new Theme();
$form = $request->all();
$md_theme->fill($form)->save();
return redirect('/dashboard');
}
-----
// お題を削除する関数
public function destroy_theme($id)
{
info('destroy_id', ['destroy_id' => $id]);
$theme = Theme::find($id)->delete();
return redirect('/dashboard');
}
web.phpの編集
ダッシュボードに関するrouteを追記
-----
Route::resource('/dashboard', 'App\Http\Controllers\DashboardController');
Route::get('/dashboard', [App\Http\Controllers\DashboardController::class, 'index']);
Route::post('/dashboard/store_theme', 'App\Http\Controllers\DashboardController@store_theme')->middleware(['auth', 'verified'])->name('dashboard.store_theme');
Route::delete('/dashboard/destroy_theme/{theme_id}', 'App\Http\Controllers\DashboardController@destroy_theme')->middleware(['auth', 'verified'])->name('dashboard.destroy_theme');
-----
動作確認
管理者しか表示できなくなっているので、デザインはどうでも良し。
お題追加
追加ボタンをクリックして、お題、カテゴリ、有効期限を入力して「登録」ボタンをクリック
お題削除
「削除」ボタンをクリック
まとめ
管理画面でのお題管理は完成。
次はトップ画面に有効期間中のお題を表示して、
お題からテーマ登録できるようにする予定。
続く