0

I am trying to convert the a MySQL query into a Laravel Eloquent query.

The following code will select a row of result where then it return the value of the weekNum column

function currentWeek() {

    $sql = "SELECT DISTINCT weekNum FROM schedule WHERE DATE_ADD(NOW(), INTERVAL -50 HOUR) < gameTimeEastern ORDER BY weekNum LIMIT 1 ";
    $query = $mysqli->query($sql);

    if ($query->num_rows > 0) {

        $row = $query->fetch_assoc();
        return $row['weekNum'];

    }
}

In Laravel in my SchedulesController this is what I am trying to achieve.

public function index()
{

    $schedules = Schedule::where('week', '=', 4)->get();

    return view('schedules.index', compact('schedules'));
}

Obviously I don't want to hard code the week in. This is my attempt.

public function index()
{
    $currentWeek = Schedule::distinct()
        ->where('gameTime', '<', Carbon::now()->addHours(100))
        ->orderBy('gameTime', 'desc')
        ->take(1)
        ->get();

    $schedules = Schedule::where('week', '=', $currentWeek->week)->get();

    return view('schedules.index', compact('schedules'));
}

But I get this error

ErrorException in SchedulesController.php line 25:
Undefined property: Illuminate\Database\Eloquent\Collection::$week
4
  • Can you do a die-dump of $currentWeek? There seems to be no week-property. Commented Oct 4, 2015 at 18:04
  • I get this Collection {#157 ▼ #items: array:1 [▼ 0 => Schedule {#158 ▼ #fillable: array:15 [▶] #connection: null #table: null #primaryKey: "id" #perPage: 15 +incrementing: true +timestamps: true #attributes: array:18 [▶] #original: array:18 [▶] #relations: [] #hidden: [] #visible: [] #appends: [] #guarded: array:1 [▶] #dates: [] #dateFormat: null #casts: [] #touches: [] #observables: [] #with: [] #morphClass: null +exists: true } ] } Commented Oct 4, 2015 at 18:19
  • You can't access property's of a collection with magic methods. For this to work you need a Model. If you only ever need one result you can replace ->get() with ->first() to directly receive the model. Commented Oct 4, 2015 at 18:21
  • That work! Can you provide a solution so I can accept your answer. Commented Oct 4, 2015 at 18:26

1 Answer 1

1

You can't access the propertys because ->get() returns a collection of objects. For this to work you only need one object of your Eloquent Model.

If you only ever need one result you can replace ->get() with ->first() to directly receive the model object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.