0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravel初心者メモ:フォーム → DB保存 → 一覧 → 詳細まで作る

0
Posted at

Laravelを触り始めて、フォーム送信からDB保存、一覧表示まで作ったので、その過程を整理する。
なお、私はVPS上で開発しているので、それっぽい話も入ります。

今回の流れ

投稿フォーム

バリデーション

DB保存

投稿一覧

投稿詳細

Laravelの流れ

Route → Controller → Model → Database → View

app/
 ├ Http/Controllers   Controller
 └ Models             Model

routes/
 └ web.php            Route

resources/
 └ views              View

database/
 ├ migrations         テーブル設計
 └ database.sqlite    SQLiteDB

データベースを用意する

Laravelは最初から SQLite が使える。
SQLiteはファイル型データベースで、MySQLのようにサーバーを立てる必要がない。

migration(テーブル作成)

migrationはテーブル設計ファイルで、php artisan migrate をターミナルで実行するとDBに反映される。
php artisan make:migration create_posts_table
database/migrations/に database/migrations/日付_create_posts_table.php ができる。
そこの元の以下の分を

public function up(): void
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->timestamps();
    });
}

↓次のようにする(追加したい要素を足す)

例
public function up(): void
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('body');
        $table->timestamps();
    });
}

ここでは$table->string('title');$table->text('body');を追記している。テーブル名はcreateの第一引数のposts

$table->id();        → id カラム(インクリメント)
$table->string();    → 文字列カラム
$table->text();      → 長文カラム

書いた後

php artisan migrateをSSH内ターミナルで実行。
cdでLaravelプロジェクトのルートディレクトリ、artisanしかないところで実行。ミスったらphp artisan migrate:freshで消せる。
php artisan make:migration create_posts_table
でmigrationファイルを作成。

Laravelの基本構造

Route - Controller - Model - Database - View

Route(routes/web.php)

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
  • 冒頭で↑を書く
    • RouteクラスとPostControllerクラスをこのファイルで使うため。Route::getなんちゃらみたいな。
    • URLと処理を結び付ける。
    • Route::get('/posts', [PostController::class, 'index']);
    • これは/postにアクセスし、PostControllerのindex()を実行する

Controller(app/Http/Controllers/PostController.php)

public function index()
{
    $posts = Post::all();

    return view('posts_index', [
        'posts' => $posts
    ]);
}
- DBから投稿を取得し、VIEWに渡す。posts_indexはブラウザで見る時のURL

Model(app/Models/Post.php)

  • データベースを操作するクラス。
  • Post::all() postsテーブルの全権取得。SELECT * FROM posts(勝手に複数形になる)
  • Post::find($id); idで1件取得。SELECT * FROM posts WHERE id = ?

View(resources/views/posts_index.blade.php)

  • 投稿を一件ずつ表示
@foreach ($posts as $post)

<h2>{{ $post->title }}</h2>
<p>{{ $post->body }}</p>

@endforeach
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?