How can I copy this code to send information to a view from Laravel Controller?

Here is my edit function in the controller

public function edit($id)
{
    $game = Game::find($id);
    // build list of team names and ids
    $allTeams = Team::all();
    $team = [];
    foreach ($allTeams as $t)
        $team[$t->id] = $t->name();
    // build a list of competitions
    $allCompetitions = Competition::all();
    $competition = [];
    foreach ($allCompetitions as $c)
        $competition[$c->id] = $c->fullname();
    return View::make('games.edit', compact('game', 'team', 'competition'));
}

I am sending data for display in a selection list. I know about Eloquent ORM method lists, but the problem is, as far as I know, it can only take property names as an argument, not methods (like name()and fullname()).

How can I optimize this, can I use Eloquent?

+4
source share
3 answers

I would have looked and . You can do what you want by adjusting your models. attributesappends

Contest

<?php namespace App;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class Competition extends Model
{

  protected $appends = ['fullname'];
  ...
  public function getFullnameAttribute()
  {
    return $this->name.' '.$this->venue;
  }
}

Team

<?php namespace App;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class Team extends Model
{

  protected $appends = ['name'];
  ...
  public function getNameAttribute()
  {
    return $this->city.' '.$this->teamName;
  }
}

controller

public function edit($id)
{
    $game = Game::find($id);
    $team = Team::get()->lists('id','name');
    $competition = Competition::get()->lists('id','fullname');
    return View::make('games.edit', compact('game', 'team', 'competition'));
}
+3
source

, ( Eloquent), toArray , .

Eg.

public function toArray()
{
    return array_merge(parent::toArray(), [
        'fullname' => $this->fullname(),
    ]);
}

- :

$competition = $allCompetitions->fetch('fullname');

, , , , ( - ), .

0

You can call the model method in the view file if they are not related to other models. Therefore, if name () and fullname () return the result associated with this model, you can use these model methods in the view

@foreach (($allTeams as $t)
    {{ $t->name() }}
@endforeach

Of course you need to transfer the $ allteams collection from the controller to view

0
source

All Articles