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?

LaravelでControllerが理解できない理由

0
Posted at

Controllerの中の独特の表現と、それでCRUDができてしまう仕組みがつながっていません。
整理してみました。

そもそも

Controllerのコードは、普通のPHP+Laravelのクラスです。

以下、PostController。
Postモデルを使ってDBからデータを取得し、
その結果をViewに渡して表示している。

public function index()
{
    $posts = Post::all();

    return view('posts_index', [
        'posts' => $posts
    ]);
}

以上はメソッドを定義し、変数にDBのデータを入れて、Viewのposts_index.blade.phpに送っている。

public function index()

クラスのメソッドです。つまり、PostController内の関数。

$posts = Post::all();

Postモデルからpostsテーブルを引っこ抜き全件取得するという意味です。
SELECT * FROM postsをしている。

::の意味

クラスの静的メソッドを呼び出すもの。
つまり、Postクラスのall()を呼びます。

Post::all();

SELECT * FROM posts

Post::find($id)

SELECT * FROM posts WHERE id = $idの意味

Post::create(['title' => 'test']);

INSERT INTO postsの意味

##それ以外の頻出

$post = Post::find($id)

::findでは、$idに含まれた1件を探して格納。
SELECT * FROM posts WHERE id = ?をやっている

$post->title

$postはPostモデルのオブジェクト。
->titleでtitleカラムの値を取得できる。
つまり、$post->titleは取得した1件のうちのタイトルを取り出す。

->save()

変更した内容をDBに保存する意味
UPDATE posts SET title=?, body=? WHERE id=?をやっている

->first()

'Post::where('title','test')->first();'
SELECT * FROM posts WHERE title = 'test' LIMIT 1

->where()

'Post::where('title','test')->get();'
SELECT * FROM posts WHERE title = 'test'

->findOrFail()

Post::findOrFail($id)
見つからなければ404

->つきと、::の違い

  • :: → データを取りに行く
  • -> → データを扱う

早くスムーズに読めるようになりたいねー!

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?