Question

i'm currently learning laravel and try to follow this tutorial. But im using laravel 4 and the tutorial is using laravel 3, so i should fix many things because of that. I have this method on a controller

public function InsertTestData()
{   
    $logged_in_user = Auth::user(); 

    $photos = array(
        array(
            'user_id' => $logged_in_user->id,
            'location' => 'http://farm6.staticflickr.com/5044/5319042359_68fb1f91b4.jpg',
            'description' => 'Dusty Memories, The Girl in the Black Beret (http://www.flickr.com/photos/cloudy-day/)'
        ),
        array(
            'user_id' => $logged_in_user->id,
            'location' => 'http://farm3.staticflickr.com/2354/2180198946_a7889e3d5c.jpg',
            'description' => 'Rascals, Tannenberg (http://www.flickr.com/photos/tannenberg/)'
        ),
        array(
            'user_id' => $logged_in_user->id,
            'location' => 'http://farm7.staticflickr.com/6139/5922361568_85628771cd.jpg',
            'description' => 'Sunset, Funset, Nikko Bautista (http://www.flickr.com/photos/nikkobautista/)'
        )
    );
    $logged_in_user->photos()->save($photos);
}

and this is the model i used

class User extends Eloquent implements UserInterface, RemindableInterface {
    public function photos()
    {
    return $this->hasMany('Photo');
    }
}

it retuns error like this

Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, array given, called in /Library/WebServer/Documents/webpraktek/app/controllers/DashboardController.php on line 44 and defined

line 44 is this line

$logged_in_user->photos()->save($photos);

this is model for class photo

class Photo extends Eloquent
{
    public function user()
    {
        return $this->belongsTo('User');
    }

    public function photocomments()
    {
        return $this->hasMany('PhotoComment');
    }
}

i dont know anything to fix this problem, since i'm still learning. why is this happen? does the different in laravel version causing this kind of error? thanks

EDIT: i fixed it with this for now,

foreach($photos as $photo) {
    $photos = new Photo();
    $photos->user_id = $photo['user_id'];
    $photos->location = $photo['location'];
    $photos->description = $photo['description'];
    $photos->save();
}
Was it helpful?

Solution

As far as I can tell, your example doesn't work because you're not creating a new Photo model.

Try replacing this:

$logged_in_user->photos()->save($photos);

with:

foreach ($photos as $photoData) {
    $photo = new Photo($photoData);
    $logged_in_user->photos()->save($photo);
}

OTHER TIPS

You don't need to use $logged_in_user to associate because you already have the ids set in the array, so just use create instead.

Photo::create($photos);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top