I'm building a very simple web app with Laravel.
I've built two separate Controllers, which each return two separate views, as follows:
ProfileController:
class ProfileController extends BaseController {
public function user($name)
{
$user = User::where('name', '=', $name);
if ($user->count())
{
$user = $user->first();
$workout = DB::table('workouts')->where('user_id', '=', $user->id)->get();
Return View::make('profile')
->with('user', $user)
->with('workout', $workout);
}
return App::abort(404);
}
}
WorkoutController:
class WorkoutController extends BaseController {
public function workout($name)
{
$workout = DB::table('workouts')->where('name', '=', $name)->first();
if ($workout)
{
Return View::make('add-exercise')
->with('workout', $workout);
}
return App::abort(404);
}
}
What is confusing me is what I had to do in order to pass a single workout
object to each view. As you might have noticed the query builders for workout
are different:
$workout = DB::table('workouts')->where('user_id', '=', $user->id)->get();
and
$workout = DB::table('workouts')->where('name', '=', $name)->first();
On the profile
view, I get an object using the ->get();
method, but on the add-exercise
view, I must use ->first();
or I will otherwise get an array with only one index, where I can then access the object, i.e. $workout[0]->name
instead of $workout->name
.
Why is this? Shouldn't I be able to use either get
and/or first
in both controllers and expect the same type of result from both since I want the same thing from the same table?
first()
will only ever return none or one object, so it can return a straight object without needing a collection – Feelervar_dump($workout)
from each, what class is each object? If I recall,->get()
should return a collection of results, while->first()
should return an object representing a single row. – Diacaustic