1

I have a HasMany relationship that works on the whole site. Just made a new controller and in this controller I have this inside a method:

  // find all galleries that need to be deleted...
    $galleries = DB::table('galleries')->where('curdeldate', '<', time())->get();

    foreach($galleries as $gallery)
    {            

        //get all the images associated with the gallery
        $photos = $gallery->photos;

this throws this message: ErrorException Undefined property: stdClass::$photos but I cannot figure out why...

I also included this:

use App\Gallery;
use App\Photo;
2
  • what do you get when you do dd($galleries) Commented Apr 18, 2020 at 14:08
  • 1
    actually that can'T work because you use DB facade... that's like getting raw data from table... it's not connected with anything... no relationships... Commented Apr 18, 2020 at 14:09

1 Answer 1

1

You should use:

$galleries = Gallery::where('curdeldate', '<', time())->get();

foreach($galleries as $gallery)
{            
    $photos = $gallery->photos;

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

2 Comments

Thank you very much it worked.. coudl you please explain what the difference is? why the other one does not work?
When you use DB facade it's like you are using raw SQL... SELECT * FROM 'galleries' and you get only data from that table... the photos are in the 'photos' table and you would have to use join photos to get the photos also... You could make it work also with DB:: but I find this approach much cleaner and since you already have the Eloquent models why not to use them.

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.