Created
June 15, 2024 14:12
-
-
Save DamianSuess/3e7e517dcca29eb3d095ecabf2cfa487 to your computer and use it in GitHub Desktop.
Laravel 11 - API and Web Sharing Controller
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
/* | |
* 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