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

More than 3 years have passed since last update.

Laravelを用いてアプリを作る。

Last updated at Posted at 2021-08-01

*本件はlaravelをインストールした状態から始める

1.アプリのインストール

1.アプリを作成する

ターミナル
composer create-project laravel/laravel アプリ名

下記のように出たらOK
application keyはメモっとくのがいいらしいい

ターミナル実行結果
php artisan key generate
application key

 2.サーバーを起動(確認)

ターミナル
/ディレクトリは作成したアプリ名/
oredayoore@MacBook-Air-5 作成したアプリ$ php artisan serve

3.URL入力

リンク
http://127.0.0.1:8000/

→画面が出る!

2.データベースを作成+設定する

1.環境変数を設定する

アプリ名/.env
1.設定するデータベース名を記述以下sqliteの場合
DB_CONNECTION = sqlite
他のDB_CONNECTION = データベース名が記述されていた場合削除すること
2.データベースの絶対パスを指定すること以下例
DB_DATABASE=/home/foobar/myproject/database/database.sqlite

2.データベースを作成する。

ターミナル
上述の環境変数を設定する』2番で設定したパス通りにデータベースを作成すること
touch /home/foobar/myproject/database/database.sqlite

3. デフォルトのデータベースを設定する。

config/database.php
    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */
//下記のsqliteの所に自分の指定したいデータベースを入れる。上述のDB_CONNECTION = sqliteの環境変数と一致させること
    'default' => env('DB_CONNECTION', 'sqlite'),

3.マイグレーションファイル作成

1.マイグレーションファイル作成

ターミナル
oredayoore@MacBook-Air-5 作成したアプリ$php artisan make:migration create_books_table --create=books
ターミナル 結果
created migrationと出れば成功

→/database/migration/配下にファイルが作成される

2.マイグレーションファイルをいじる

/database/migration/

    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
        //いじるのはここ!↓ 参考)$table->型(カラム名);
                        
            $table->id();
            $table->string('title');
            $table->timestamps();

        });
    }

3.マイグレーションファイル更新(忘れがち)

ターミナル
oredayoore@MacBook-Air-5作成したアプリ$php artisan migrate

4.モデルの作成

1.モデルの作成

ターミナル
oredayoore@MacBook-Air-5作成したアプリ$php artisan make:model Book(モデル名)
//ここのモデル名の命名規則は頭文字は大文字、単数系

→/app/models/Book.phpにモデルファイルが作成される

5.ビューファイルを追加する

1.ビューファイルを追加

books.blade.php(自分でHTMLファイルを作成してみましょう)
@extends('layouts.app')

@section('content')
	<div class="container">
		<div class="col-sm-offset-2 col-sm-8">
			<div class="panel panel-default">
				<div class="panel-heading">
					新たに書籍を追加する
				</div>

				<div class="panel-body">
					<!-- Display Validation Errors -->
					@include('commons.errors')

					<!-- New Book Form -->
					<form action="/book" method="POST" class="form-horizontal">
						{{ csrf_field() }}

						<!-- Book Name -->
						<div class="form-group">
							<label for="task-name" class="col-sm-3 control-label">Book</label>

							<div class="col-sm-6">
								<input type="text" name="name" id="book-name" class="form-control" value="{{ old('book') }}">
							</div>
						</div>

						<!-- Add Book Button -->
						<div class="form-group">
							<div class="col-sm-offset-3 col-sm-6">
								<button type="submit" class="btn btn-default">
									<i class="fa fa-plus"></i>本を追加する
								</button>
							</div>
						</div>
					</form>
				</div>
			</div>

			<!-- Books -->
			@if (count($books) > 0)
				<div class="panel panel-default">
					<div class="panel-heading">
						書籍一覧
					</div>

					<div class="panel-body">
						<table class="table table-striped task-table">
							<thead>
								<th>書籍タイトル</th>
								<th>&nbsp;</th>
							</thead>
							<tbody>
								@foreach ($books as $book)
									<tr>
										<td class="table-text"><div>{{ $book->title }}</div></td>

										<!-- Task Delete Button -->
										<td>
											<form action="/book/{{ $book->id }}" method="POST">
												{{ csrf_field() }}
												{{ method_field('DELETE') }}

												<button type="submit" class="btn btn-danger">
													<i class="fa fa-trash"></i>削除
												</button>
											</form>
										</td>
									</tr>
								@endforeach
							</tbody>
						</table>
					</div>
				</div>
			@endif
		</div>
	</div>
@endsection


*注意
一番上の
use App\models\Book;
は、モデルのパスを表しているので
必ず一致されるようにしましょう!

主な語句の説明

@extends('layouts.app')

@section('content')

@include('commons.errors')

@book→データベースから抽出したデータを表示されます。
そのためには後述の『ルーティング』で設定してあげる必要があります。

追加されたファイルを格納するパスの例)
resources/views/layouts/
resources/views/layouts/
resources/views/layouts/

ルーティングの設定
WEBアプリケーションは必ずルーティングという見えない管を通じてVIEWを表示させたりデータベースを引っ張っていくので
これを設定してあげなければVIEWも表示されない

books.blade.php(自分でHTMLファイルを作成してみましょう)

<?php

use App\models\Book;
use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
//画面遷移のルーティング
$booksはビューに表記されている
Bookというモデルクラスのallという関数によってデータベースのデータを全て呼び出して
booksに代入している
だからデータベースのデータをビューに表示することができる
//

Route::get('/', function () {
    $books = Book::all();
    return view('books',['books' => $books]);
});

//データ送信のルーティング
送信するには
送信先のパスが必要になる
それが下記の例post('/book' 
$validatorはデータ入力の制御何でもかんでも受け入れる賭けにはいかない
またデータを保存するには例のviewにある$bookという変数に入力値を代入してモデルまで送らなければならない
その処理が
    $book = new Book;
    $book->title = $request ->name;
    $book->save();
である
//
Route::post('/book' , function(Request $request){
    $validator = Validator::make($request->all(),[
        'name' => 'required|max255', 
 ]);
    $book = new Book;
    $book->title = $request ->name;
    $book->save();

    return redirect('/');
})->middleware('auth');




Route::delete('/book/{book}',function(Book $book){
    $book->delete();

    return redirect('/');

});
Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

【解説】
ルーティングを作成するイメージとして、通信する度にルーティングの設定が必要になる
例)
ページに移動→Route::get
データを送信→Route::post
画像を削除→Route::delete、、などなど

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