/** * Store a newly created resource in storage. * * @return Response */ public function store(Request $req) { $tag = strtolower($req->input('tag')); $validator = Validator::make($req->all(), ['tag' => 'required|unique:hashtags,name']); if ($validator->fails()) { //Already Exists } else { $hashtag = new Hashtag(); $hashtag->name = $tag; //Insert hashtag into mysql db $hashtag->save(); } //get user $user = Auth::user(); //get hashtag $hashtag = Hashtag::where('name', $tag)->first(); $relationExists = count(DB::select('select * from hashtag_user where hashtag_id = ? and user_id = ?', [$hashtag->id, $user->id])); //Check relation does not exist already if ($relationExists > 0) { //If relation exists return response()->api(400, 'no', 'Error before hashtag attachment, relation already exists', ''); // exists } else { //if it does not exist //Create relation hashtag-user $hashtag->users()->attach($user->id); //this executes the insert-query //Macro format JSON response return response()->api(200, 'yes', 'Success attaching hashtag to user', ''); } }