skip to Main Content

I`ve got code that shows all of the placements for a user. Is there a way to narrow this down to only show placements that are in the future? I’ve tried to do this using where and carbon::now to no avail.

My current code to show all of the placements :

$placements = Auth::user()->placementsAuthored;
$placements->load('keystage', 'subject', 'dates');

Placements Authored connection to connect a user to a placement :

public function placementsAuthored()
{
    return $this->hasMany(Placement::class, 'author_id');
}

My attempt at trying to do this. I get no errors but the code doesn’t work. It doesn’t seem to take any effect of my where clause any ideas?

$placements ->where('date','>',Carbon::now()->format('Y-m-d'));

2

Answers


  1. Chosen as BEST ANSWER

    After a bit of tweaking, I found that this works but I don't understand why this works and the above doesn't. In my mind, they do the same but this is a longer way of doing it. Any idea why this works and the above doesn't?

    // Only load future placements
    $placements = Placement::whereHas( 'dates',
        function ($q) {
        $user_id = Auth::user()->id;
        $q->where('author_id', $user_id)->where('date','>=' ,Carbon::now()->format('Y-m-d'));})->get();
    

  2. You should take a different name for the date column because the date keyword is already reserved in the PHP function this is not a standard way

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search