0
0

More than 3 years have passed since last update.

Laravel入門メモ

Last updated at Posted at 2021-08-21

項目

  1. アプリケーション用のディレクトリを作成
  2. Webサーバの起動確認
  3. viewをいじってみる
  4. DBとの接続設定
  5. DBを操作する為のモデル,コントローラ,マイグレーションファイルを作成
  6. ルーティングの設定
  7. DBから持ってきたデータをテンプレートへ送る
  8. 特定のデータをDBから取得する

1. アプリケーション用のディレクトリを作成

作業ディレクトリ内にlaravelアプリケーション作成用のディレクトリを作成する。

$ laravel new laravel_test

これで配下にlaravel_testが作成される。

2. Webサーバの起動確認

Webサーバが起動するか確認をして、laravelが正常に動いていることを確かめる。

$ cd laravel_test
$ php artisan serve

3. viewをいじってみる

resources/views/welcome.blade.phpが前項で表示されたテンプレート。
この中身をいじって動きを確認する。

4. DBとの接続設定

laravel側から色々とDBを操作出来る。
.envを開いて、

DB_CONNECTION=mysql(postgresならpgsql)
DB_HOST=127.0.0.1(ホスト名)
DB_PORT=3306(ポート)
DB_DATABASE=laravel_test(事前に作成したDB名)
DB_USERNAME=(ユーザ名)
DB_PASSWORD=(パスワード)

これでDBとの接続が完了。

5. DBを操作する為のモデル,コントローラ,マイグレーションファイルを作成

$ php artisan make:model (モデル名) -m -c -r
今回は
$ php artisan make:model Article -m -c -r

作成されたdatabase/migrations配下から一番下を選んで、

public function up()
    {
        Schema::create('(ここを操作出来る(table名))', function (Blueprint $table) {
            $table->increments('id');
            $table->string('content');
            //$table->データ型('カラム名');
        });
    }

その後、

$ php artisan migrate

これで接続したDBに自動的にテーブルが作成される。

6. ルーティングの設定

routes/web.phpにてルーティングを設定する。

Route::get('/', function () {
    return view('welcome');
    // 通常のlaravelって出てくるやつへのルーティング
});

Route::get('/articles', 'App\Http\Controllers\ArticleController@index')->name('article.list');
//Route::get('ルーティングの指定URL', 'フルPATH@後々説明するコントローラ内でのfunction')->name('article.list')

このルーティングが使える様に、app/Providers/AppServiceProvider.phpにて

public function boot()
    {
        //
    }
//を
public function boot()
    {
        \URL::forceScheme('http');
    }
//にする

その後、app/Http/Controllers/モデル名Controller.php:(今回はapp/Http/Controllers/ArticleController.php:)にて、

//前項で後々説明するとしたfunction index()内を編集する
public function index()
    {
        $message = 'Hello World';
        // $変数 = ???にて変数を定義

        return view('index', ['message' => $message]);
     //return view('テンプレートファイル', ['渡す名前' => 変数]);
        //これも後々出るが、テンプレートファイル名は???.blade.phpの.blade.phpを抜いていいっぽい?
    }

その後resources/viewsにてindex.blade.phpを作成し、

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    {{$message}}
</body>
</html>

その後php artisan serveし、http://127.0.0.1:8000/articlesする事でHello Worldが完了する。

7. DBから持ってきたデータをテンプレートへ送る

まずapp/Http/Controllers/ArticleController.phpを開いて

public function index()
    {
        $message = 'Welcome my BBS';
        //↓これを追加する
        $articles = Article::all();
     //$変数 = モデル名::all();
        //これで接続したDB中の自分が操作したテーブルにおけるデータを全取得する
        return view('index', ['message' => $message,"send_article" => $articles]);
        //送る際は他の変数と同様
    }

そしてresources/views/index.blade.phpにて

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    {{$message}}
    @foreach ($send_article as $i)
        <p>{{$i -> content}}</p>
        // -> ???でカラムを指定出来る
        //今回はcontentカラムのみを出力する形
    @endforeach
</body>
</html>

これでDBからデータを取得、テンプレートで表示が完了。

8. 特定のデータをDBから取得する

routes/web.phpにて追記

routes/web.php
Route::get('/articles/{id}', 'App\Http\Controllers\ArticleController@show')->name('article.show');

その後app/Http/Controllers/ArticleController.phppublic function show()

ArticleController.php
public function show(Request $request, $id,Article $article)
{
    //前述の{id}を変数として受け取っている
    $message = 'This is your article ' . $id;
  //find()メソッドを使うときは引数は主キー
   //主キーの配列を入れてもOK
   //主キー以外で指定するやつは後述する
    $article = Article::find($id);
    return view('show', ['message' => $message, 'article' => $article]);
}

その後show.blade.phpを作成し、

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    {{$message}}
    //リンク中の/{id}にて指定されたレコードのcontentカラムを出力
    <p>{{ $article->content }}</p>
    //index.~~を出力するルーティングはarticle.listと名付けてある為、そこへ偏位するよという事
    <a href={{ route('article.list') }}>一覧に戻る</a>
</body>
</html>

これでhttp://127.0.0.1:8000/articles/0とかにアクセスするといい感じに出力される。

また、index.blade.phpにて

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    {{$message}}
    @foreach ($article as $i)
            <p>
          //article.showはshow.~~へルーティンングする
                //$article(全てのDBレコードが入っている)の中のidカラムをarticles/{id}のidとしてforeachで入力
                <a href='{{ route("article.show", ["id" =>  $i->id]) }}'>
          //表示はcontentカラムの中身
                    {{ $i->content }}
                </a>
            </p>
        @endforeach
</body>
</html>

これで各データ個別ページに移動できるリンクを表示している

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