0

I am writing an assignment system for radio newscasts. The data tables:

station
id | calls
---| -----
 1 | cxri

newscast
id | name_input | for_station_id
---|------------|---------------
 1 | am         |  1

assignment
id | newscast_id | user_id
 1 |       1     |  5

The controller for Assignment.edit is as follows:

if (! Gate::allows('assignment_edit'))
    return abort(401);
    }
    $relations = [
        'anchors' => \App\User::get()->pluck('name', 'id')->prepend('Please select', ''),
        'casts' => \App\Newscast::get()->pluck('name_input', 'id')->prepend('Please select', ''),
    ];

    return view('assignment.create', $relations);

The Newscasts model:

public function for_station()
{
    return $this->belongsTo(Station::class, 'for_station_id')->withTrashed();
}

Right now I get

"casts" => Collection {#451 ▼
    #items: array:2 [▼
      "" => "Please select"
      1 => "am"
    ]
}

I want

"casts" => Collection {#451 ▼
    #items: array:2 [▼
      "" => "Please select"
      1 => "cxri-am"
    ]
}

How do I make that happen?

Or should I denormalize the data and make name_input 'cxri-am' instead of 'am'?

What I've tried:
Accepted answer in Laravel pluck fields from relations

'casts' => \App\Newscast::with('station')->get()->pluck('name_input', 'id'),

errors with

Call to undefined relationship [station] on model [App\Newscast]

I included the Newscast model above based on the discussion in Laravel: get/show data from related tables. Based on that discussion it appears to me the newscast should already be able to access the Station calls. But as shown above, the calls are not in $casts.

Community
  • 1
  • 1
Scott Roberts
  • 13
  • 1
  • 7

1 Answers1

1

You are close with what you have tried. The with() function needs the name of the relation function, not the table, so this should work for getting the relation model loaded:

'casts' => \App\Newscast::with('for_station')->get(),

As for getting the data to concat the way you want, I would make an accessor on the Newscast model that will return the data you want:

function getNameInputStationAttribute() {
    return $this->for_station->calls . "-" . $this->input_name;
}

You would then use this like:

'casts' => \App\Newscast::with('for_station')->get()->pluck('name_input_station', 'id')->prepend('Please select', ''),

If I could point out a few other things, the return code of 401 indicates Unauthenticated whereas 403 indicates Unauthorized which would be more applicable to the Gate returning false. Also, class functions should be cammel case, so your for_station function should be forStation or even just station.

Jacob Lambert
  • 7,449
  • 8
  • 27
  • 47
  • Thank you, @JRLambert ! This worked beautifully. I will also make some of the other changes you mentioned, and appreciate your pointers! – Scott Roberts Apr 30 '17 at 04:49