I am trying to save hashtags to a database. At the moment they are saved in a single row with the image_id and the following format:
Hashtags: #test bla #test #test
DB: test,test,test
What do I have to do to save every single hashtag in a single database row maintaining the correstpondig photo_id?
Here is how I save the hashtags:
$hashtag = new Hashtag;
$hashtag->photo_id = $photo->id;
$hashtag_string = Input::get('hashtags');
$str = $hashtag_string;
preg_match_all('/#([^\s]+)/', $str, $matches);
$hashtags_final = implode(',', $matches[1]);
$hashtag->hashtag = $hashtags_final;
$hashtag->save();
Depending on your needs there is several solutions:
First: you can loop through hashtags and save them with correct image_id. like this:
$hashtag_string = Input::get('hashtags');
preg_match_all('/#([^\s]+)/', $hashtag_string, $matches);
//looping through matched items in your $matches array
foreach($matches as $tag)
{
$hashtag = new Hashtag();
$hashtag->image_id = $photo->id;
$hashtag->hashtag = $tag;
$hashtag->save();
}
Second: create Many-to-Many type of relation between Image
and Hashtag
and use full power of it. You can find everything in the oficial docs on creating and using