3
Help us understand the problem. What are the problem?

More than 1 year has 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>
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
3
Help us understand the problem. What are the problem?