1
0

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

Posted at

Laravel について

MVC アーキテクチャについて

Laravel は MVC(Model-View-Controller)アーキテクチャを採用しています。MVC とは、以下の 3 つの要素に分かれた設計パターンです。

  • Model(モデル): データベースとやり取りし、ビジネスロジックを担う部分
  • View(ビュー): ユーザーに表示される画面部分
  • Controller(コントローラー): Model と View を仲介し、リクエストを処理する部分

これにより、コードの保守性が向上し、役割が明確になります。

ルーティングについて

Laravel では、ルーティングを使用して URL と処理を結びつけます。ルートは routes/web.php に定義します。

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/hello', function () {
    return 'Hello, Laravel!';
});

コントローラーを使ったルーティングも可能です。

Route::get('/users', [UserController::class, 'index']);

マイグレーションについて

マイグレーションは、データベースのスキーマを管理する機能です。新しいテーブルを作成するには、以下のコマンドを実行します。

php artisan make:migration create_users_table

生成されたマイグレーションファイル (database/migrations/xxxx_xx_xx_xxxxxx_create_users_table.php) を編集し、スキーマを定義します。

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamps();
});

マイグレーションを適用するには、次のコマンドを実行します。

php artisan migrate

Eloquent ORMについて

Eloquent ORM は、Laravel のデータベース操作を簡単にする ORM(オブジェクト・リレーショナル・マッピング)です。モデルを作成し、データベースとやり取りできます。

php artisan make:model User

app/Models/User.php に Eloquent モデルが作成されます。データの取得は以下のように行います。

$users = User::all();

特定のデータを取得する場合:

$user = User::find(1);

データの作成:

$user = new User;
$user->name = 'John Doe';
$user->email = 'john@example.com';
$user->save();

Blade テンプレートエンジンについて

Blade は Laravel のテンプレートエンジンで、簡単に HTML を作成できます。

resources/views/layout.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>@yield('title')</title>
</head>
<body>
    @yield('content')
</body>
</html>

resources/views/home.blade.php:

@extends('layout')

@section('title', 'ホームページ')

@section('content')
    <h1>Laravel へようこそ</h1>
@endsection

CRUD 処理について

CRUD(Create, Read, Update, Delete)処理は、Laravel の基本的なデータ操作です。

データの作成 (Create)

$user = User::create([
    'name' => 'Alice',
    'email' => 'alice@example.com'
]);

データの取得 (Read)

$users = User::all();

データの更新 (Update)

$user = User::find(1);
$user->name = 'Updated Name';
$user->save();

データの削除 (Delete)

$user = User::find(1);
$user->delete();

以上が Laravel の基本的な機能についての紹介です。初心者でもこの流れを理解すれば、簡単なアプリを作成できるようになります。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?