LoginSignup
4
7

More than 3 years have passed since last update.

Laravelでモデルのメソッドを呼び出す

Posted at

単純にモデルに記述したメソッドをコントローラーで呼び出したい時に、どう記述するかを学んだので備忘録でまとめます。

Customer.php
  // 男性の割合を計算
  public function mens()
  {
    $all = Customer::all()->count();
    $mens_num = Customer::where('gender', 0)->count();
    $mens_percent = round($mens_num / $all * 100);
    return $mens_percent;
  }

  // 女性の割合を計算
  public function womens()
  {
    $all = Customer::all()->count();
    $womens_num = Customer::where('gender', 1)->count();
    $womens_percent = round($womens_num / $all * 100);
    return $womens_percent;
  }
コントローラー.php
  public function productReport()
  {
    $customer = new Customer;
    $mens = $customer->mens();
    $womens = $customer->womens();
    return view('product_report',compact('mens', 'womens'));
  }

new モデル名でインスタンスを作成してからメソッドを呼び出します。

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