LoginSignup
0

More than 1 year has passed since last update.

posted at

updated at

40 代おっさん Laravelのモデルクラスでメソッドを使ってみる。

本記事ついて

本記事は プログラミング初学者の私が学習していく中でわからない単語や概要をなるべくわかりやすい様にまとめたものです。
もし誤りなどありましたらコメントにてお知らせいただけるとありがたいです。

構築環境

・EC2:Amazon Linux2
・PHP7.3
・Laravel 5.8
・mariadb

前回の記事からの続きですので、こちらを見てくださるとうれしいです。

クラスの拡張

以前Personクラスを作ったのでそちらを拡張

public function getData()
{
   return $this->id . ':' . $this->name . ' (' . $this->age . ')'; 
}

上を書き加える。

次に
index.blade.phpを修正

<table>
    <tr><th>Data</th></tr>
    @foreach ($items as $item)
        <tr>
            <td>{{$item->getData()}}</td>
        </tr>
    @endforeach
</table>

これで見て見るとid,name,ageがまとまったはずです。

IDによる検索

findメソッドはIDによるレコード検索を行うのに用意されたメソッド

$変数 = モデルクラス :: find( 整数 );

テーブルのプライマリーキーは「id]という整数値のフィールドであるという前提で実行している。

findアクションを作る

find.blade.phpを作成

viewaファルダのpersonフォルダ内に作ってください。
コードは

<form action="/person/find" method="post">
    @csrf
    <input type="text" name="input" value="{{$input}}">
    <input type="submit" value="find">
</form>
@if (isset($item))
<table>
    <tr><th>Data</th></tr>
    <tr>
        <td>{{$item->getData()}}</td>
    </tr>
</table>
@endif
PersonControllerの修正
    public function find(Request $request)
    {
        return view('person.find',['input' => '']);
    }

    public function search(Request $request)
    {
        $item = Person::find($request->input);
        $param =['input' => $request->input, 'item' => $item];
        return view('person.find', $param);
    }

find   /findにGEtアクセスしたときの処置
search  送信されたinputフィールドの値を引数に指定してfindメソッドを呼び出す。

$item = Person::find($request->input);
IDによる検索

ルート情報の追加

web.phpに

Route::get('person/find', 'PersonController@find');
Route::post('person/find', 'PersonController@search');

whereによる検索

ID以外の検索は
whereメソッドを使う

複数のレコードを得る
$変数 = モデルクラス :: where( フィールド名 , 値 )->get();

最初のレコードだけを得る
$変数 = モデルクラス :: where( フィールド名 , 値 )->first();

whereで検索の条件を設定し、getまたはfirstを使ってレコードを取得

nameを検索

searchを書き換え

public function search(Request $request)
    {
        $item = Person::where('name',$request->input)->first();
        $param =['input' => $request->input, 'item' => $item];
        return view('person.find', $param);
    }

$item = Person::where('name',$request->input)->first();
nameの値でレコードを収得しています。

参考資料

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
What you can do with signing up
0