Skip to content

Instantly share code, notes, and snippets.

@DamianSuess
Created June 15, 2024 14:12
Show Gist options
  • Save DamianSuess/3e7e517dcca29eb3d095ecabf2cfa487 to your computer and use it in GitHub Desktop.
Save DamianSuess/3e7e517dcca29eb3d095ecabf2cfa487 to your computer and use it in GitHub Desktop.
Laravel 11 - API and Web Sharing Controller
/*
* Example showing how to share an API route with a Web (view)
* If the request expects JSON, it shall receive it. Otherwise, display the View.
* Remember, just because you can, doesn't mean you should.
*/
class ActivityController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
// Show the view and pass variables to it
$perPage = 15;
$activities = Activity::orderBy("Name", "asc")->paginate($perPage);
// Handles both API and Web requests
if (request()->expectsJson() && request()->is('api/v1/*'))
{
// Return JSON goodness
return $activities;
}
else
{
return view(
"activity.index",
compact("activities")
)->with("i", (request()->input("page", 1) - 1) * $perPage);
}
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment