Laravel Eloquent many-to-many attach
laravel, mysql, php
Solution
Thanks @Collin i noticed i misunderstand i made my check yesterday
$album = $user->album()->where_album_id($album_id)->get();
if(empty($album))
{
$user->album()->attach($album_id);
}
Problem
I am new to laravel, and trying to build a photo album with it. My problem is that i use the attach function to insert the user id and group id to my database, it works okay, but in the documentation it says this about the attach function For example, perhaps the role you wish to attach to the user already exists. Just use the attach method: So i wanted to use it the same way, if the `album_id` already exist just update it, other wise insert thr new one, but my problem is it always insters, it does not checks if the `album_id` already exsits My model ``` class User extends Eloquent { public static $timestamps = false; public function album() { return $this->has_many_and_belongs_to('album', 'users_album'); } } ``` Post function ``` public function post_albums() { $user = User::find($this->id); $album_id = Input::get('album'); $path = 'addons/uploads/albums/'.$this->id.'/'. $album_id . '/'; $folders = array('path' => $path, 'small' => $path. 'small/', 'medium' => $path. 'medium/', ); if (! is_dir($path) ) { foreach ($folders as $folder) { @mkdir($folder, 0, true); } } $sizes = array( array(50 , 50 , 'crop', $folders['small'], 90 ), array(164 , 200 , 'crop', $folders['medium'], 90 ), ); $upload = Multup::open('photos', 'image|max:3000|mimes:jpg,gif,png', $path) ->sizes( $sizes ) ->upload(); if($upload) { $user->album()->attach($album_id); return Redirect::back(); } else { // error show message remove folder } } ``` Could please someone point out what im doing wrong? Or i totally misunderstod the attach function?