LoginSignup
1
2

More than 1 year has passed since last update.

Laravel基礎、view、ブログ一覧ページ

Last updated at Posted at 2022-03-04

<画面設計における**ワイヤーフレーム**とは>

  • WEBページのレイアウトを定めるもの
  • 完成イメージを作る。

<LaravelにおけるBladeとは>

  • Blade→Laravelでviewを作るためのテンプレートエンジン→見た目を作る手助けをしてくれる。
  • ワイヤーフレームの作成 (Google Drive)→diagrams.netを使用する。

開発用Gitブランチを新規作成

実行コマンド
//必ずLaravelのrootディレクトリに移動してからbranchを作る。
cd ~/environment/ディレクトリ名
git checkout -b ブランチ名

❶view(ビュー)を表示する。

  • ルーティングファイルの配置場所は、routes/web.php
  • ルーティングとは、HTTPリクエストを検知したとき、それを受け付けるか受け付けないかの判断をする。
  • 下記の場合は、routes/web.php内のpostsフォルダ内にあるindex.blade.phpを指定している。
routes/web.php
Route::get('/', function () {
    return view('posts/index');
//postsフォルダ内のindex.blade.phpを指定。.blade.php省略
});

❷画面に表示したいファイルはresouces内のviews内にある.blade.phpファイルに書いていく

index.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">

        <title>Blog</title>

       
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@200;600&display=swap" rel="stylesheet">

       
   </head>
    <body>
        <h1>Blog Name</h1>Ï
        <div class="posts">
            @foreach($posts as $post)
            <div class="post">
                <h2 class="title">{{$post->title}}</h2>
                <p class="body">{{$post->body}}</p>
            </div>
            @endforeach
        </div>
    </body>
</html>

❸起動していく

実行コマンド
php artisan serve --port= ~

❶contorollerの段階でデータを取得してviewに返す方法。

routes/web.php
Route::get('/',PostContoroller@index) //'/'の時にPostContorollerのindexメソッドを実行

withメソッドを使う

  • ViewにController内で取得した変数を渡したい場合は、Viewインスタンスに対してwithメソッドを使用する。
  • with('変数名' => 値)→ContorollerからViewにデータを呼び出せるようになる。
  • PostContorollerファイルを下記のように修正↓
PostContoroller.php
public function index(Post $post) //function 関数名(Post $post)とは、変数に、Postクラスのインスタンスを代入しているというころである。→メソッドインジェクション
    {
    return view('posts/index')->with(['posts' =>$post->get()]);
    }
//->get()で全件データを取得

❸view側でデータを受け取って表示するようにする。
index.blade.phpに埋め込んでいく.

  • 変数をbladeファイル内に書く時は、**{{$post}}**となる。→{{}}で囲む。
  • @foreach($posts as $post) {} @endforeachで囲む。
index.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">

        <title>Blog</title>


        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@200;600&display=swap" rel="stylesheet">


   </head>
    <body>
        <h1>Blog Name</h1>Ï
        <div class="posts">
            @foreach($posts as $post) //$posts(変数)は、return view('posts/index')->with(['posts' =>$post->get()]);でviewに渡す時に指定している
            <div class="post">
                <h2 class="title">{{$post->title}}</h2>
                <p class="body">{{$post->body}}</p>
//postsテーブルから取得している。
            </div>
            @endforeach
        </div>
    </body>
</html>
/*
+----+--------+----------------+---------------------+---------------------+------------+
| id | title  | body           | created_at          | updated_at          | deleted_at |
+----+--------+----------------+---------------------+---------------------+------------+
|  3 | title3 | This is body3. | 2021-10-19 18:23:28 | 2021-10-19 18:23:28 | NULL       |
|  4 | title4 | This is body4. | 2021-10-19 18:23:41 | 2021-10-19 18:23:41 | NULL       |
+----+--------+----------------+---------------------+---------------------+------------+
//❶mysql -u dbuser -pでログイン
    ❷use データベース名でデータベース切り替え
    ❸select * from テーブル名で、中身を表示。
  */

データ取得と表示の応用


 
->get()で全件取得してしまうのはまずいので、最大件数を指定したり、取得するデータの条件を指定する。

データベースとのデータのやりとりを行う、Postモデル(Post.php)を編集する。

  • 条件は最大10件まで表示で、新しい順に表示↓
  • 関数の引数には型を指定できる(array、bool、float、int、string、クラス名・インスタンス名など)
Post.php
public function getByLimit(int $limit_count = 10)
{
//updated_atで新しい順に並べた後、limitで制限をかける。
return $this->orderBy('updated_at' ,'DESC')->limit($limit_count)->get();
//(例) orderBy('id',desc)または[asc]
//limit関数でデータから取得する件数を指定

モデルクラスの修正完了
コントローラークラスを修正する。

PostContoroller.php
public funcion index(Post $post)
{
return view('posts/index')->width(['posts'=>$post->getByLimit()]);

❷ページネーション設定
paginate

Post.php
 public function getPaginateByLimit(int $limit_count = 10)
    {
        return $this->orderBy('updated_at','DESC')->paginate($limit_count);
    }
  • 上記を実行すると今までのCollecrtionインスタンスではなく、Paginationインスタンスが返ってくるようになる。
PostController.php
 public function index(Post $post)
    {
    return view('posts/index')->with(['posts' =>$post->getPaginateByLimit(1)]); //関数部分変更
    }

❸viewファイルにpaginate追加

view/index.blade.php
<div class="paginate">
{{$posts->links}}
</div>
 
1
2
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
2