Tuesday, March 21, 2017

Add a custom function to a model to retreive specific data

I'm building an app to evaluate children in a nursery school. (my wife is a nursery school teacher). This are the basic models and relations:

class Subevaluation extends Model
{
    // fields: id, title, date, classroom, course_id
    public function subevaluations(){
       return $this->hasMany('App\Subevaluation');
    }
}

class Evaluation extends Model
{
    // fields: id, child_id, evaluation_id, quotation
    public function evaluation(){
       return $this->belongsTo('App\Evaluation');
    }
}

There are more models in my app (Child, Classroom,...) but the above 2 are the important ones for this issue.

Now I can retrieve all subevaluations of one selected evaluation; for example:

$eval = App\Evaluation::find(1);

$subevals = $eval->subevaluations;

And in my view I can list all the subevaluations:

@foreach($eval->subevaluations as $subeval)

  <td> </td>
  <td> </td>
  <td> </td>

@endforeach

Here comes my question: (drumrolls...)

I want to be able to list the last 5 quotations made for this specific evaluation/course. So, in the @foreach loop, I want some kind of function like that returns an array like this:

array{
  {
    'quot' => 'A',
    'date' => '2017-03-01',
    'info' => 'info here'
  },
  {
    'quot' => 'C',
    'date' => '2017-02-14',
    'info' => 'info here'
  },
  {
    'quot' => 'A',
    'date' => '2017-01-30',
    'info' => 'info here'
  },
  {
    'quot' => 'B',
    'date' => '2016-12-04',
    'info' => 'info here'
  },
  {
    'quot' => 'A',
    'date' => '2016-11-20',
    'info' => 'info here'
  }
}

Then I can loop this array an show this info in the view

How can I achieve this in Laravel? (version 5.4)

Thank you!



via John Wings

Advertisement