LoginSignup
3
4

More than 3 years have passed since last update.

モデルメソッドの使い方

Posted at

メソッドを定義してuseして使うだけ

# 使い方(Personモデルでの例)
use App\Person; #コントローラでuse

$person = Person::all(); #インスタンス取得
$Person->モデルメソッド(); #メソッドを使用

viewで表示する例:

Person.php
    # メソッド定義
  public function getData()
  {
    return $this->id . ':' . $this->name . '(' . $this->age . ')';
  }
PersonController.php

use App\Person;
use Illuminate\Http\Request;

class PersonController extends Controller
{
  public function index(){
    $people = Person::all();
    return view('person.index', ['people' => $people]);
  }
}

person/index.blade.php
  <table>
    @foreach($people as $person)
    <tr>
    <!-- ここでメソッド呼び出し -->
      <td>{{ $person->getData() }}</td>
    </tr>
    @endforeach
  </table>
3
4
1

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
3
4