Create Search API in laravel 11

  <?php


namespace App\Http\Controllers;

use App\Models\Student;
use Illuminate\Http\Request;

class StudentController extends Controller
{
    public function getData($id = null)
    {
        return $id ? Student::find($id) : Student::all();
    }

    public function addStudent(Request $request)
    {
        $student = new Student;
        $student->name = $request->name;
        $student->email = $request->email;
        $result = $student->save();
        if ($result) {
            return ["result" => "Student added successfully"];
        } else {
            return ["result" => "Something went wrong"];
        }
    }

    public function updateStudent(Request $request)
    {
        $student = Student::find($request->id);
        $student->name = $request->name;
        $student->email = $request->email;
        $result = $student->save();
        if ($result) {
            return ["result" => "Student updated successfully"];
        } else {
            return ["result" => "Something went wrong"];
        }
    }

    public function deleteStudent($id)
    {
        $student = Student::findOrfail($id);
        $result = $student->delete();
        if ($result) {
            return ["result" => "record deleted successfully"];
        }
        return ["result" => "record deleted successfully" . $id];
    }

    public function searchStudent($name)
    {
        return Student::where("name", "like", "%" . $name . "%")->get();
    }
}
Above File is app\Http\Controllers\StudentController.php File





Below File is app\Models\Student.php File
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    public $timestamps = false;
    protected $table = "students";
    protected $fillable = ["name", "email"];
}






Below File is database\json\students.json File
[
    {
        "name": "Sandeep",
        "email": "sandeep@gmail.com"
    },
    {
        "name": "Sanjeev",
        "email": "sanjeev@gmail.com"
    },
    {
        "name": "Hemant",
        "email": "hemant@gmail.com"
    },
    {
        "name": "Rajesh",
        "email": "rajesh@gmail.com"
    },
    {
        "name": "Suresh",
        "email": "suresh@gmail.com"
    },
    {
        "name": "Aditya",
        "email": "aditya@gmail.com"
    }
]






Below File is database\migrations\2025_01_13_060337_create_students_table.php File
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->string("email", 50)->unique();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('students');
    }
};






Below File is database\seeders\DatabaseSeeder.php File
<?php

namespace Database\Seeders;

use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // User::factory(10)->create();

        // User::factory()->create([
        //     'name' => 'Test User',
        //     'email' => 'test@example.com',
        // ]);

        $this->call([
            StudentSeeder::class
        ]);
    }
}






Below File is database\seeders\StudentSeeder.php File
<?php

namespace Database\Seeders;

use App\Models\Student;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;

class StudentSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $json = File::get(path: "database\json\students.json");
        $student = collect(json_decode($json));

        $student->each(function ($student) {
            Student::create([
                "name" => $student->name,
                "email" => $student->email
            ]);
        });
    }
}






Below File is routes\api.php File
<?php

use App\Http\Controllers\StudentController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:sanctum');

Route::controller(StudentController::class)->group(function () {
    Route::get("/list/{id?}", "getData");
    Route::post("/add-student", "addStudent");
    Route::put("/update-student", "updateStudent");
    Route::delete("/delete-student/{id}", "deleteStudent");
    Route::get("/search-student/{name}", "searchStudent");
});



Comments

Popular posts from this blog

Eloquent Many to Many Relationship Tutorial in Laravel 11

Eloquent with JSON Data Columns Tutorial in Laravel 11

Blade Template Tutorial Three Template Inheritance in Laravel 11