HackMD
  • Prime
    Prime  Full-text search on all paid plans
    Search anywhere and reach everything in a Workspace with Prime plan.
    Got it
      • Create new note
      • Create a note from template
    • Prime  Full-text search on all paid plans
      Prime  Full-text search on all paid plans
      Search anywhere and reach everything in a Workspace with Prime plan.
      Got it
      • Options
      • Versions and GitHub Sync
      • Transfer ownership
      • Delete this note
      • Template
      • Save as template
      • Insert from template
      • Export
      • Dropbox
      • Google Drive
      • Gist
      • Import
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
      • Download
      • Markdown
      • HTML
      • Raw HTML
      • Sharing Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • More (Comment, Invitee)
      • Publishing
        Everyone on the web can find and read all notes of this public team.
        After the note is published, everyone on the web can find and read this note.
        See all published notes on profile page.
      • Commenting Enable
        Disabled Forbidden Owners Signed-in users Everyone
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
        • Everyone
      • Invitee
      • No invitee
    Menu Sharing Create Help
    Create Create new note Create a note from template
    Menu
    Options
    Versions and GitHub Sync Transfer ownership Delete this note
    Export
    Dropbox Google Drive Gist
    Import
    Dropbox Google Drive Gist Clipboard
    Download
    Markdown HTML Raw HTML
    Back
    Sharing
    Sharing Link copied
    /edit
    View mode
    • Edit mode
    • View mode
    • Book mode
    • Slide mode
    Edit mode View mode Book mode Slide mode
    Note Permission
    Read
    Owners
    • Owners
    • Signed-in users
    • Everyone
    Owners Signed-in users Everyone
    Write
    Owners
    • Owners
    • Signed-in users
    • Everyone
    Owners Signed-in users Everyone
    More (Comment, Invitee)
    Publishing
    Everyone on the web can find and read all notes of this public team.
    After the note is published, everyone on the web can find and read this note.
    See all published notes on profile page.
    More (Comment, Invitee)
    Commenting Enable
    Disabled Forbidden Owners Signed-in users Everyone
    Permission
    Owners
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Invitee
    No invitee
       owned this note    owned this note      
    Published Linked with GitHub
    Like4 BookmarkBookmarked
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    PHPerのための「Laravel 入門を語り合う」PHP TechCafe ================================================= # Laravel クイックスタート ## Laravel導入手段 参考:[PHPerのための「Laravel/PHP8/Dockerで開発環境作りを語り合う」TechCafe](https://hackmd.io/@hrxVDayfRGeTR-1JBV3QLA/H1NeB2asD) - Docker系 - [Laravel Sail](https://readouble.com/laravel/8.x/ja/installation.html#your-first-laravel-project)(Laravel公式Docekr環境) - LaravelのDocker開発環境を操作するための軽量コマンドラインインタフェイス - 以下のサービスを合わせて利用できる - MySQL - PostgreSQL - MariaDB - Redis - Memcached - MeiliSearch - MinIO - Selenium - MailHog - [laradock](https://laradock.io/) - いわゆる全部入りのLaravel Docker環境 - 設定ファイルを修正して独自の環境が作成可能 - 例えば、PHP7 + PostgreSQL + Nginx みたいな自分好みの環境が作れる - プロジェクトのディレクトリ配置されている箇所に新しくLaradocを配置するだけでよいのでプロジェクトをDockerコンテナ上にマウントさせるだけなら比較的すぐに始められる - [vessel](https://vessel.shippingdocker.com/) - こちらも同じくLaravel Docker環境 - PHP8.0に対応していない - PHP 7.4, MySQL 5.7, Redis(最新), NodeJS(最新)、NPM、Yarn、Gulp - [docker-laravel](https://github.com/ucan-lab/docker-laravel) - ucanさんのOSS - 日本語で解説があるので入りやすい - https://qiita.com/ucan-lab/items/5fc1281cd8076c8ac9f4 - ローカルマシン系 - [Composerで自分でいれる](https://readouble.com/laravel/8.x/ja/installation.html#installation-via-composer) - 導入後 `php artisan serve` で立ち上がる - 直接プロジェクトを作る or インストーラを導入してからプリジェクトを作る - DBは sqlite でOK - [Laravel Jetstream](https://jetstream.laravel.com/1.x/introduction.html) も利用可能 - [Valet](https://readouble.com/laravel/8.x/ja/valet.html) - 軽量であることが売りのmacOS向けLaravel開発環境 - 極端なマシンスペックでの開発や、速度重視の場合に利用 - Laravel以外のFWでも利用可(Cake PHPや、Symfony、Lumenなど) - DBマネージャのDBnginを使うことで PostgreSQL、MySQL、Redis などが利用可能 - Homebrew 必須 - 仮想環境系 - [Homestead](https://readouble.com/laravel/8.x/ja/homestead.html) - Vagrant を使ったLaravel開発環境 - Vagrant が仮想化ソフト(VirtualBoxなど)の管理と事前設定をすべてやってくれる - 実態としては仮想環境上の Ubuntu 上で Laravel の実行環境ができあがる - Vagrant と 仮想化ソフト(VirtualBox or Parallels)が必須 -------------------------- ## 大まかな流れ * Laravel Sail でサービス起動 * 処理の流れ紹介 * ルーティング * Controller * Blade * Controller 作成 * Blade 作成 * Controller から Blade にパラメータを返す * ToDoアプリを作成する * Migrationを作成する * Seederを作成する * Modelを作成する * Controller側に処理を追加する * Modelを利用してDBアクセスする ## WSL2 の環境に Laravel Sail の環境を作成する手順 公式リファレンス https://laravel.com/docs/8.x/installation#getting-started-on-linux ※Laravel Sail を導入する環境に docker と docker-compose がインストールされていること ```bash= # laravel-todo-app というプロジェクトの環境作成 curl -s https://laravel.build/laravel-todo-app | bash # Laravel Sail による開発環境起動 cd laravel-todo-app ./vendor/bin/sail up # 初回起動はDockerコンテナ作成にかなり時間がかかる # http://localhost/ にアクセス # Laravel の初期画面が表示される ``` ### Docker のセキュリティ機能によりプロジェクト作成に失敗する場合は以下を確認 https://qiita.com/nasuB7373/items/92166d7958044ab8d450 ## 処理の流れ ### ルーティング * [Routing](https://laravel.com/docs/8.x/routing#the-default-route-files) * `routes/web.php ` にリクエストURLと対応する処理を記述する * web.php からViewを返すこともできる * コントローラに処理を回すこともできる * 基本的はコントローラに処理を回すことが圧倒的に多いと思われる * Laravel で新規プロジェクトを作成した際は以下が初期設定されている ```php= Route::get('/', function () { return view('welcome'); }); ``` * 上記は`http://localhost` にアクセスすると `welcome.blade.php` を返すという処理になっている * view() メソッドは `resources/view` 配下の引数指定されたファイルをViewとして表示する処理 #### ルーティング基礎 * `web.php` に以下を追加 ```php= Route::get('/hello', function () { return view('hello'); }); ``` * `resources/views` 配下に `hello.blade.php` というファイルを新規作成 * 以下のHTMLを記述 ```htmlmixed= <h1>PHPerのための「Laravel 入門を語り合う」PHP TechCafe</h1> <div> <p>Hello World!</p> </div> ``` * `http://localhost/hello` にアクセス * 上記のHTMLが表示される ### Viewにパラメータを追加 * `web.php` に追加した処理を以下の通り修正 ```php= Route::get('/hello/{name}', function ($name) { return view('hello',['name' => $name]); }); ``` * `resources/views/hello.blade.php` を以下の通り修正 ```htmlmixed= <h1>PHPerのための「Laravel 入門を語り合う」PHP TechCafe</h1> <div> <p>Hello World!</p> @isset($name) <p>Hello {{$name}}!</p> @endisset </div> ``` * `http://localhost/hello/Rakus` にアクセス * Hello Rakus! と画面に表示される [view](https://laravel.com/docs/8.x/views#introduction) の参考ページ ### Controller 作成 * Laravel の artisan のコマンドで Controller を作成 * [Laravel Sail](https://laravel.com/docs/8.x/sail#executing-artisan-commands) で [artisan](https://laravel.com/docs/8.x/artisan#introduction) コマンドを実行する際は以下を実行 ```bash= cd laravel-todo-app ./vendor/bin/sail artisan make:controller HelloController ``` * `Http/controllers` 配下に `HelloController` が追加される ```php= <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class HelloController extends Controller { // } ``` * HelloController に以下のような index メソッドを追加する ```php= <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class HelloController extends Controller { public function index() { return view('hello'); } } ``` * `web.php` に Controller のルーティングを記載 ```php= // 追加した Controller を use に追加 use App\Http\Controllers\HelloController; // 省略 // Controller のルーティングを追加 Route::get('/hello', [HelloController::class, 'index']); ``` * `http://localhost/hell` にアクセス * Controller の index メソッドが呼び出され View を表示できる ### Controller から View にパラメータを渡す * HelloController の index メソッドを以下の通り修正 ```php= <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class HelloController extends Controller { public function index() { return view('hello', ['name' => 'Rakus']); } } ``` * `http://localhost/hell` にアクセス * Controller から渡された値を View にセットできる * [Controller](https://laravel.com/docs/8.x/controllers#basic-controllers) の参考ページ ### ToDo アプリを作成する * タスクを追加・編集・削除が可能なToDoアプリを作成する * まずは以下のような構成のテーブルを作成する * id * integer * task * text * timestamp * timestamp ### Migration について * テーブル定義の作成 * Migration ファイルを作成しておけばテーブル定義を簡単に共有できる * アプリケーションの構築も `artisan` コマンドを1回実行するだけでOK * 以下のコマンドを実行する ```bash= cd laravel-todo-app ./vendor/bin/sail artisan make:migration create_todo_table ``` * `database/migrations` 配下に `YYYY_MM_DD_XXXXXXX_create_todos_table.php` というファイルが作成される * 中身は以下の通り ```php= <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTodoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('todo', function (Blueprint $table) { $table->id(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('todo'); } } ``` * up メソッドの中を修正してテーブル定義を作成する * なお、設定可能な列の一覧は以下 * [Available Column Types](https://laravel.com/docs/8.x/migrations#available-column-types) ```php= public function up() { Schema::create('todo', function (Blueprint $table) { $table->id(); $table->text('task'); $table->timestamps(); }); } ``` 以下コマンドを実行してテーブルを作成 ```bash= cd laravel-todo-app ./vendor/bin/sail artisan migrate ``` * なお、テーブル定義を新しく作り直す場合は列だけを追加する Migration を作成しなくても、既存の Migration を修正し以下コマンドでテーブルを再作成できる ```bash= cd laravel-todo-app ./vendor/bin/sail artisan migrate:fresh ``` [Migration](https://laravel.com/docs/8.x/migrations#introduction) の参考ページ ### Seeder を登録する * Seeder を利用することでアプリケーションの初期データを登録できる * 以下コマンドを実行する ```bash= cd laravel-todo-app ./vendor/bin/sail artisan make:seeder TodosSeeder ``` * `database/seeders` 配下に `TodoSeeder` というファイルが作成される * 中身は以下の通り ```php= <?php namespace Database\Seeders; use Illuminate\Database\Seeder; class TodosSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // } } ``` * runメソッドの中身を以下の通り修正 ```php= public function run() { DB::table('todos')->insert([ 'task' => 'PHPの勉強' ]); DB::table('todos')->insert([ 'task' => 'Laravelの勉強' ]); DB::table('todos')->insert([ 'task' => 'PHPTechCafeへの参加' ]); } ``` * 以下コマンドを実行してSeederを登録 ```bash= cd laravel-todo-app ./vendor/bin/sail artisan db:seed --class=TodosSeeder ``` [Seeder](https://laravel.com/docs/8.x/seeding#introduction) の詳細ページ ### Model について * Laravel で利用可能な ORM として Eloquent を利用するとDBアクセスの処理が容易に書ける * 以下コマンドで `todo` テーブルにアクセスするための Model を作成する ```bash= cd laravel-todo-app ./vendor/bin/sail artisan make:model Todo ``` [Model](https://laravel.com/docs/8.x/eloquent#generating-model-classes) の詳細ページ ### Model を利用する * Model を利用して `登録`, `編集`, `削除` を実行する * 登録 * [Inserts](https://laravel.com/docs/8.x/eloquent#inserts) * 編集 * [Updates](https://laravel.com/docs/8.x/eloquent#updates) * 削除 * [Delete](https://laravel.com/docs/8.x/eloquent#deleting-models) ### Todoアプリ用の各種データを登録する * 新規作成 * TodoController * Todoアプリ用のController * todo.blade.php * TodoアプリのView * 各種ファイルの中身は GitHub のソース参照 * [web.php](https://github.com/MasaKuuuu/laravel-todo-app/blob/main/routes/web.php) * [TodoController](https://github.com/MasaKuuuu/laravel-todo-app/blob/main/app/Http/Controllers/TodoController.php) * [Request](https://laravel.com/docs/8.x/requests#introduction) の処理を追加していることに注意 * 一覧表示は各種メソッド内で index() メソッドの戻り値を取得するようにしている * [todo.blade.php](https://github.com/MasaKuuuu/laravel-todo-app/blob/main/resources/views/todo.blade.php) * POSTなどのリクエスト時は `@csrf` を form に含めていないとリクエスト処理時にエラーになるため注意 * [詳細](https://laravel.com/docs/8.x/csrf#csrf-introduction) * web.php のルーティング変更 * `/todo/index` * Todoリストを取得 * `/todo/create` * タスクを追加 * `/todo/edit` * タスクを編集 * `/todo/delete` * タスクを削除 * `http://localhost/todo` にアクセス * 各主動作の確認 ## おまけ:Resource Controllers https://laravel.com/docs/8.x/controllers#resource-controllers 手軽にREST APIを作成するためのテクニック

    Import from clipboard

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lost their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template is not available.


    Upgrade

    All
    • All
    • Team
    No template found.

    Create custom template


    Upgrade

    Delete template

    Do you really want to delete this template?

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in via Google

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Tutorials

    Book Mode Tutorial

    Slide Mode Tutorial

    YAML Metadata

    Contacts

    Facebook

    Twitter

    Feedback

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions

    Versions and GitHub Sync

    Sign in to link this note to GitHub Learn more
    This note is not linked with GitHub Learn more
     
    Add badge Pull Push GitHub Link Settings
    Upgrade now

    Version named by    

    More Less
    • Edit
    • Delete

    Note content is identical to the latest version.
    Compare with
      Choose a version
      No search result
      Version not found

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub

        Please sign in to GitHub and install the HackMD app on your GitHub repo. Learn more

         Sign in to GitHub

        HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Available push count

        Upgrade

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Upgrade

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully