public function newTweet(Request $request) { $this->validate($request, ['content' => 'required|max:140']); $newTweet = new Tweet(); $newTweet->content = $request->content; $newTweet->user_id = \Auth::user()->id; $newTweet->save(); //Process Tags $tags = explode('#', $request->tags); $tagsFormatted = []; //clean up the tags foreach ($tags as $tag) { if (trim($tag)) { $tagsFormatted[] = strtolower(trim($tag)); } } //Loop over each tag foreach ($tagsFormatted as $tag) { //Grab the first matching result OR insert this new unique tag $theTag = Tag::firstOrCreate(['name' => $tag]); $allTagIds[] = $theTag->id; } //Attacth the Tag IDs to the tweet $newTweet->tags()->attach($allTagIds); return redirect('profile'); }
public function newTweet(Request $request) { $this->validate($request, ['content' => 'required|min:2|max:140']); $newTweet = new Tweet(); // point to columns in db $newTweet->content = $request->content; // user who is logged in take their id $newTweet->user_id = \Auth::user()->id; // Save into database $newTweet->save(); // Process the tags $tags = explode('#', $request->tags); $tagsFormatted = []; // clean up tags, remove white spaces foreach ($tags as $tag) { // if after trimming something remains if (trim($tag)) { $tagsFormatted[] = strtolower(trim($tag)); } } $allTagIds = []; // Loop over eah tag foreach ($tagsFormatted as $tag) { // Grab the first matching result or insert this new unique tag // if tag is present will not insert into db. If not present, inserts into db. $theTag = Tag::firstOrCreate(['name' => $tag]); $allTagIds[] = $theTag->id; } // Attach the tag ids to the tweet $newTweet->tags()->attach($allTagIds); return redirect('profile'); }
public function newTweet(Request $request) { $this->validate($request, ['content' => 'required|max:140']); $newTweet = new Tweet(); $newTweet->content = $request->content; $newTweet->user_id = \Auth::user()->id; $newTweet->save(); $tags = explode(' ', $request->tags); $tagsFormatted = []; foreach ($tags as $tag) { //clean up newly created tags array. if (trim($tag)) { $tagsFormatted[] = strtolower(trim($tag)); } } //loop over each tag foreach ($tagsFormatted as $tag) { //loop over each formatted tag and grab the first matching result or add new tag to db $theTag = Tag::firstOrCreate(['name' => $tag]); $allTagIds[] = $theTag->id; } $newTweet->tags()->attach($allTagIds); return redirect('profile'); }