Created
December 27, 2019 12:48
-
-
Save SethBuilder/7b04b2265e2db2ae5cf8bc153dadf7de to your computer and use it in GitHub Desktop.
Code Sample from Envago.io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use Illuminate\Http\Request; | |
use App\Activity; | |
use App\Like; | |
use Auth; | |
use App\Http\Resources\Like as LikeResource; | |
class LikeController extends Controller | |
{ | |
/** | |
* Store a newly created like in storage. Also return updated likes. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @return \Illuminate\Http\Response | |
*/ | |
public function postLike(Request $request) | |
{ | |
$slug = $request->get('slug'); | |
$id = Auth::id(); | |
// Pull activity to like | |
$activity = Activity::where('slug', $slug)->first(); | |
if ($activity) { | |
if ($id) { | |
$like = Like::where([['activity_id', $activity->id], ['user_id', $id]])->first(); | |
} else { | |
$like = Like::where([['activity_id', $activity->id], ['ip', $request->ip()]])->first(); | |
} | |
if ($like) { | |
$like->like = !$like->like; | |
$like->ip = $request->ip(); | |
$like->save(); | |
} else { | |
$like = new Like; | |
$like->user_id = $id ? $id : null; | |
$like->activity_id = $activity->id; | |
$like->logged_in_status = $id ? true : false; | |
$like->ip = $request->ip(); | |
$like->like = true; | |
$like->save(); | |
} | |
return response()->json(['count' => $activity->likes()->where('like', true)->count()], 200); | |
} else { | |
return response()->json(false); | |
} | |
} | |
/** | |
* Display all like for admin analytics. | |
* | |
* @return \Illuminate\Http\Response | |
*/ | |
public function index() | |
{ | |
$likes = Like::all(); | |
return LikeResource::collection($likes); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment