Skip to content

Instantly share code, notes, and snippets.

@abdullaadnan
Created December 6, 2020 13:47
Show Gist options
  • Save abdullaadnan/439236d9b93bdfcf5dcf5b5769641b5f to your computer and use it in GitHub Desktop.
Save abdullaadnan/439236d9b93bdfcf5dcf5b5769641b5f to your computer and use it in GitHub Desktop.
Building and Consuming a RESTful API in Laravel PHP
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Student;
class ApiController extends Controller
{
public function getAllStudents() {
$students = Student::get()->toJson(JSON_PRETTY_PRINT);
return response($students, 200);
}
public function createStudent(Request $request) {
$student = new Student;
$student->name = $request->name;
$student->course = $request->course;
$student->save();
return response()->json([
"message" => "student record created"
], 201);
}
public function getStudent($id) {
if (Student::where('id', $id)->exists()) {
$student = Student::where('id', $id)->get()->toJson(JSON_PRETTY_PRINT);
return response($student, 200);
} else {
return response()->json([
"message" => "Student not found"
], 404);
}
}
public function updateStudent(Request $request, $id) {
if (Student::where('id', $id)->exists()) {
$student = Student::find($id);
$student->name = is_null($request->name) ? $student->name : $request->name;
$student->course = is_null($request->course) ? $student->course : $request->course;
$student->save();
return response()->json([
"message" => "records updated successfully"
], 200);
} else {
return response()->json([
"message" => "Student not found"
], 404);
}
}
public function deleteStudent ($id) {
if(Student::where('id', $id)->exists()) {
$student = Student::find($id);
$student->delete();
return response()->json([
"message" => "records deleted"
], 202);
} else {
return response()->json([
"message" => "Student not found"
], 404);
}
}
}
@abdullaadnan
Copy link
Author

Restful API in laravel

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment