Laravel基礎
Laravelのルーティングについてweb.phpの使い方(src/routes/web.php)
- URLとどのファイルを表示させるか紐づけます
- URLパラメータの受け取りをします
Laravelコントローラーの役割
Laravelでは、ルートで処理されるリクエストの処理を、コントローラーに記述します。
artisanコマンドでコントローラーを作成
# 基本的なコントローラー作成
php artisan make:controller UserController
▼app/Http/Controllers/UserController.phpが作成されます
namespace App\Http\Controllers; // 名前空間の自動設定
class UserController extends Controller // クラスの自動生成
{
// 基本的なメソッド(--resourceオプション使用時)
public function index() { } // 一覧表示
public function show($id) { } // 詳細表示
}
app/Http/Controllers
ディレクトリに新しいファイルを作成- 基本的なクラス構造を自動生成
- 必要な名前空間とクラスのインポートを設定
laravelインストール
▼バージョン確認(php composer node.js npm)
※MAMP/htdocs/作業フォルダにて
PS C:\MAMP\htdocs\step01> php -v
PHP 8.2.9 (cli) (built: Aug 1 2023 12:41:16) (NTS Visual C++ 2019 x64)
Copyright (c) The PHP Group
Zend Engine v4.2.9, Copyright (c) Zend Technologies
PS C:\MAMP\htdocs\step01> composer --version
Composer version 2.7.1 2024-02-09 15:26:28
PS C:\MAMP\htdocs\step01> node -v
v18.17.1
PS C:\MAMP\htdocs\step01> npm -v
9.6.7
参考サイト:https://readouble.com/
▼Composerのcreate-project
コマンドで新しいLaravelプロジェクトを作成
PS C:\MAMP\htdocs\step01> composer create-project laravel/laravel umarche "8.*" --prefer-dist
※umarcheというフォルダを作成
▼umarcheに移動しサーバを起動
PS C:\MAMP\htdocs\step01> cd umarche
PS C:\MAMP\htdocs\step01\umarche> php artisan serve
Starting Laravel development server: http://127.0.0.1:8000
[Tue Apr 2 10:37:07 2024] PHP 8.2.9 Development Server (http://127.0.0.1:8000) started
→記載されているURLにて表示を確認
初期設定確認
DB
PHPMYADMIN
▼MAMP PREFERENCES Ports
AMP PREFERENCES Ports
- apache port:8888
- mysql port: 8889
Open WebStart Page → TOOLS → PHPMYADMIN
日本語に設定Appearance settings
データベース名:laravel_umarcheでデータベースを新規作成
▼ユーザ登録
- Privileges(特権)タブを選択
- Add user account
- ユーザ名:umarche
- ホスト名:%
- パスワード:pas123
- Grant all privileges on database laravel\_umarche.にチェックが入っているか確認
- go(実行)→ユーザが追加される
laravel側で記載
▼umarch/.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=8889
DB_DATABASE=laravel_umarche
DB_USERNAME=umarche
DB_PASSWORD=pas123
▼接続を確認
PS C:\MAMP\htdocs\step01\umarche> php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (161.48ms)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (155.42ms)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated: 2019_08_19_000000_create_failed_jobs_table (179.04ms)
Migrating: 2019_12_14_000001_create_personal_access_tokens_table
Migrated: 2019_12_14_000001_create_personal_access_tokens_table (419.47ms)
GitHubでリポジトリを作成
Gitのインストール
コマンドプロンプトを起動しインストールを確認
※Windowsにて
C:\Users\xxxx>git --version
git version 2.44.0.windows.1
※VSCodeのターミナルの場合インストール後一度開きなおす必要があるかも
github Create a new repository
Repository name*:
laravel_umarche2
VSCodeターミナルで下記コマンド
- git init
- git add -A
- git add README.md git commit -m “first commit”
- git branch -M main
- git remote add origin git@github.com:idatokiya/laravel_umarche2.git
- git push -u origin main
エラーメッセージ対処→https://ntorelabo.com/?p=7427#co-index-5
初期設定
ブランチを分けて作業
→VSCodeターミナル下記コマンド
PS C:\MAMP\htdocs\step01\umarche> git switch -c sec01_initialSetting
Switched to a new branch 'sec01_initialSetting'
PS C:\MAMP\htdocs\step01\umarche> git branch
main
* sec01_initialSetting
タイムゾーン 言語設定
config/app.phpを編集
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'Asia/Tokyo',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'Ja',
デバッグバーインストール
composer require barryvdh/laravel-debugbar
→composer.jsonにて確認
"require": {
"php": "^7.3|^8.0",
"barryvdh/laravel-debugbar": "^3.7",
"fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "^7.0.1",
"laravel/framework": "^8.75",
"laravel/sanctum": "^2.11",
"laravel/tinker": "^2.5"
},
コミット
git add -Aでwarning
PS C:\MAMP\htdocs\step01\umarche> git add -A
warning: in the working copy of 'composer.json', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'composer.lock', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'config/app.php', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'storage/debugbar/.gitignore', LF will be replaced by CRLF the next time Git touches it
→対応
参考サイト:https://qiita.com/WebEngrChild/items/133484ca79fc90a207d5
git config --global core.autoCRLF false
▼再度git add -A
PS C:\MAMP\htdocs\step01\umarche> git add -A
PS C:\MAMP\htdocs\step01\umarche> git commit -m "initialSetting"
[sec01_initialSetting 6e98bfa] initialSetting
4 files changed, 158 insertions(+), 3 deletions(-)
create mode 100644 storage/debugbar/.gitignore
PS C:\MAMP\htdocs\step01\umarche> git push origin sec01_initialSetting
Enumerating objects: 13, done.
Counting objects: 100% (13/13), done.
Delta compression using up to 12 threads
Compressing objects: 100% (7/7), done.
Writing objects: 100% (7/7), 1.68 KiB | 858.00 KiB/s, done.
Total 7 (delta 5), reused 0 (delta 0), pack-reused 0 (from 0)
remote: Resolving deltas: 100% (5/5), completed with 5 local objects.
remote:
remote: Create a pull request for 'sec01_initialSetting' on GitHub by visiting:
remote: https://github.com/idatokiya/laravel_umarche2/pull/new/sec01_initialSetting
remote:
To github.com:xxx/laravel_umarche2.git
* [new branch] sec01_initialSetting -> sec01_initialSetting
PS C:\MAMP\htdocs\step01\umarche>
Viteの採用について
LaravelのビルドツールがLaravel Mix→Viteに変更(2022/6/28~)
Laravel Breezeインストール
Laravel Breezetとは認証ライブラリのひとつで、ログイン、ユーザ登録、パスワードリセット、メールの検証、パスワードの確認などの認証機能をシンプルに実装できます。
Tailwind CSSを使用します。
▼Gitのブランチ変更
PS C:\MAMP\htdocs\step01\umarche> git switch -c sec02_larabelBreeze
Switched to a new branch 'sec02_larabelBreeze'
PS C:\MAMP\htdocs\step01\umarche> git branch
main
sec01_initialSetting
* sec02_larabelBreeze
PS C:\MAMP\htdocs\step01\umarche>
▼composerでLaravel Breezeのパッケージをインストール
composer require laravel/breeze "1.*" --dev
PS C:\MAMP\htdocs\step01\umarche> composer require laravel/breeze "1.*" --dev
./composer.json has been updated
Running composer update laravel/breeze
Loading composer repositories with package information
Updating dependencies
Lock file operations: 1 install, 0 updates, 0 removals
- Locking laravel/breeze (v1.10.0)
Writing lock file
Installing dependencies from lock file (including require-dev)
Nothing to install, update or remove
Package fruitcake/laravel-cors is abandoned, you should avoid using it. No replacement was suggested.
Package swiftmailer/swiftmailer is abandoned, you should avoid using it. Use symfony/mailer instead.
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: barryvdh/laravel-debugbar
Discovered Package: facade/ignition
Discovered Package: fruitcake/laravel-cors
Discovered Package: laravel/breeze
Discovered Package: laravel/sail
Discovered Package: laravel/sanctum
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.
80 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
> @php artisan vendor:publish --tag=laravel-assets --ansi --force
No publishable resources for tag [laravel-assets].
Publishing complete.
No security vulnerability advisories found.
▼アセットをコンパイル
PS C:\MAMP\htdocs\step01\umarche> php artisan breeze:install
Breeze scaffolding installed successfully.
Please execute the "npm install" && "npm run dev" commands to build your assets.
PS C:\MAMP\htdocs\step01\umarche> npm install
npm WARN deprecated stable@0.1.8: Modern JS already guarantees Array#sort() is a stable sort, so this library is deprecated. See the compatibility table on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#browser_compatibility
npm WARN deprecated @babel/plugin-proposal-object-rest-spread@7.20.7: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-object-rest-spread instead.
added 805 packages, and audited 806 packages in 34s
102 packages are looking for funding
run `npm fund` for details
1 moderate severity vulnerability
To address all issues (including breaking changes), run:
npm audit fix --force
Run `npm audit` for details.
PS C:\MAMP\htdocs\step01\umarche> npm run dev
> dev
> npm run development
> development
> mix
● Mix █████████████████████████ emitting (95%)
emit
● Mix █████████████████████████ done (99%) plugins
WebpackBar:done
✔ Mix
Compiled successfully in 3.27s
Laravel Mix v6.0.49
✔ Compiled Successfully in 3254ms
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬──────────┐
│ File │ Size │
├─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼──────────┤
│ /js/app.js │ 707 KiB │
│ css/app.css │ 31.8 KiB │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴──────────┘
▼php artisan serve
で表示を確認するとLogin Registerの追加を確認
問題)Login Register画面の表示がおかしい(CSSがあたっていない)
参考コード:https://github.com/aokitashipro/laravel_umarche/blob/main/resources/views/layouts/app.blade.php
▼resources/views/layouts/guest.blade.phpを編集
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap">
<!-- Scripts -->
<!-- @vite(['resources/css/app.css', 'resources/js/app.js']) -->
<!-- Styles -->
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
</head>
<body>
<div class="font-sans text-gray-900 antialiased">
{{ $slot }}
</div>
</body>
</html>
▼resources/views/layouts/guest.app.phpを編集
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap">
<!-- Scripts -->
<!-- @vite(['resources/css/app.css', 'resources/js/app.js']) -->
<!-- Styles -->
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
</head>
<body class="font-sans antialiased">
<div class="min-h-screen bg-gray-100">
@include('layouts.navigation')
<!-- Page Heading -->
<header class="bg-white shadow">
<div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
{{ $header }}
</div>
</header>
<!-- Page Content -->
<main>
{{ $slot }}
</main>
</div>
</body>
</html>
php artisan serve
で改めて表示を確認すると正しく表示されることを確認
▼commit
PS C:\MAMP\htdocs\step01\umarche> git config --global core.autoCRLF false
PS C:\MAMP\htdocs\step01\umarche> git add -A
PS C:\MAMP\htdocs\step01\umarche> git commit -m "add Breeze"
[sec02_larabelBreeze 991eeb2] add Breeze
53 files changed, 35895 insertions(+), 5 deletions(-)
PS C:\MAMP\htdocs\step01\umarche> git push origin sec02_laravelBreeze
Enumerating objects: 99, done.
Counting objects: 100% (99/99), done.
Delta compression using up to 12 threads
Compressing objects: 100% (72/72), done.
Writing objects: 100% (78/78), 250.66 KiB | 2.02 MiB/s, done.
Total 78 (delta 24), reused 0 (delta 0), pack-reused 0 (from 0)
remote: Resolving deltas: 100% (24/24), completed with 10 local objects.
remote:
remote: Create a pull request for 'sec02_laravelBreeze' on GitHub by visiting:
remote: https://github.com/idatokiya/laravel_umarche2/pull/new/sec02_laravelBreeze
remote:
To github.com:idatokiya/laravel_umarche2.git
* [new branch] sec02_laravelBreeze -> sec02_laravelBreeze
日本語化
▼新しいブランチを作成
PS C:\MAMP\htdocs\step01\umarche> git switch -c sec02_japaneseLocalization
Switched to a new branch 'sec02_japaneseLocalization'
PS C:\MAMP\htdocs\step01\umarche> git branch
main
sec01_initialSetting
* sec02_japaneseLocalization
sec02_laravelBreeze
▼日本語化対応ファイルを作成(laravel_umarche/resources/langディレクトリ)
- ja.json
- ja/auth.php
- ja/pagination.php
- ja/passwords.php
- ja/validation-inline.php
- ja/validation.php
参考:https://github.com/idatokiya/laravel_umarche2/tree/sec02_japaneseLocalization
▼commit
PS C:\MAMP\htdocs\step01\umarche> git config --global core.autoCRLF false
PS C:\MAMP\htdocs\step01\umarche> git add -A
PS C:\MAMP\htdocs\step01\umarche> git commit -m "日本語化対応"
[sec02_japaneseLocalization a867cfb] 譌・譛ャ隱槫喧蟇セ蠢
7 files changed, 268 insertions(+)
create mode 160000 laravel_umarche
create mode 100644 resources/lang/ja.json
create mode 100644 resources/lang/ja/auth.php
create mode 100644 resources/lang/ja/pagination.php
create mode 100644 resources/lang/ja/passwords.php
create mode 100644 resources/lang/ja/validation-inline.php
create mode 100644 resources/lang/ja/validation.php
PS C:\MAMP\htdocs\step01\umarche> git push origin sec02_japaneseLocalization
Enumerating objects: 14, done.
Counting objects: 100% (14/14), done.
Delta compression using up to 12 threads
Compressing objects: 100% (11/11), done.
Writing objects: 100% (11/11), 4.55 KiB | 1.52 MiB/s, done.
Total 11 (delta 1), reused 0 (delta 0), pack-reused 0 (from 0)
remote: Resolving deltas: 100% (1/1), completed with 1 local object.
remote:
remote: Create a pull request for 'sec02_japaneseLocalization' on GitHub by visiting:
remote: https://github.com/idatokiya/laravel_umarche2/pull/new/sec02_japaneseLocalization
remote:
To github.com:idatokiya/laravel_umarche2.git
* [new branch] sec02_japaneseLocalization -> sec02_japaneseLocalization
Tailwindcss ver3
php artisan serve
だけだと反映されない(Laravel側の簡易サーバでフロント側:Node.jsは見れない)
→npm run dev
やnpm run watch
で反映
npm run watch
随時、コンパイル
ターミナル1: npm run watch
ターミナル2: php artisan serve
ターミナル3: Laravel各コマンド実行
21. 準備 (ルート->コントローラ->ビュー)
Laravelをさくらインターネットで使用する方法
SSH を利用
TeraTermをダウンロード
SSHプロトコルでサーバーを遠隔操作できるターミナルエミュレータで、Windows対応のフリーソフトです。
▼接続設定
- ホスト:初期ドメイン(xxxxxx.sakura.ne.jp)…さくらインターネットコントロールパネルで確認できます
- ユーザ名:アカウント …さくらインターネットコントロールパネルで確認できます
- パスフレーズ:さくらインターネットコントロールパネルログインパスワード
Welcome to FreeBSD!
の表示で接続の確認ができます
▼終了方法について
Tera Term のデフォルトでは、ログイン先サーバからログアウトしたり、ネットワークエラー等で接続が切れたりすると、同時に終了されます。