Building a Simple Laravel Backend for API Integration (without Views)
As a .NET developer, I frequently engage with APIs in my development tasks. Occasionally, I utilize Laravel backend for database-related work. Now, I'd like to walk you through a straightforward process of crafting our own backend.
You have to have Laravel installed, XAMPP installed, and Visual Studio Code as your code editor. That's all.
Step 1: Set Up the Project
laravel new yourProjectName
3. Move into the project directory
cd yourProjectName
4. Open from the Visual Studio Code
code .
Step 2: Configure the Database
DB_CONNECTION=mysq
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_username
DB_PASSWORD=database_password
Step 3: Generate a Controller
Launch a new terminal within Visual Studio Code and execute your PHP code there.
php artisan make:controller PostController
2. Open the created controller .php file in the app/Http/Controllers directory. (in my case its PostController.php)
3. Implement your API methods. (Lets implement after create the Model)
**Important
use Illuminate\Http\Response; // Import the Response class
use Illuminate\Http\Request;
Step 4: Create API Routes
Route::middleware('auth:sanctum')->get('/user', function (Request $request)
{
return $request->user();
});
Route::get('/get', [PostController::class, 'index']);
Route::post('/post', [PostController::class, 'store']);
Route::delete('/delete/{id}', [PostController::class, 'destroy']);
3. Connect our controller here (in the top of the api.php for my case)
use App\Http\Controllers\PostController;
Step 5: Set Up Model and Migration
let's work with the database using migrations. It's important to note that the database connection settings should be properly configured in the .env file. This ensures that our application communicates effectively with the database.
php artisan make:model Post -m
2. Open the migration file in the database/migrations directory and open the named migration file (in my case its date_timestamp_create_posts_table.php).
3. Design the table that you want to create. (in my case I'm going to create posts table in the database with id, title, content columns)
Recommended by LinkedIn
When designing the tables, remember to use plural nouns for the table names.
public function up(
{
//columns
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
)
4. Run the migration to create the table
php artisan migrate
5. Open the created model and make the fields editable. (in may case in post )
class Post extends Model //model name is singular
{
protected $fillable = ['title', 'content', 'created_at', 'updated_at'];
}
**created_at and updated_at columns creating automatically.
6. Navigate to the api.php file, where we define our routes, and include the model
use App\Models\Post;
Step 6: Implement API Logic
class PostController extends Controlle
{
//get data
public function index()
{
$posts = Post::all(); // Retrieve all posts from the database
return response()->json($posts, Response::HTTP_OK); // Return the data as JSON
}
//post
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|max:255',
'content' => 'required',
]);
// Create a new Post instance with the validated data
$post = new Post([
'title' => $validatedData['title'],
'content' => $validatedData['content'],
]);
$post->save(); // Save the new post to the database
return response()->json($post, Response::HTTP_CREATED); // Return the new post as JSON
}
//delete
public function destroy($id)
{
$post = Post::find($id);
if (!$post) {
return response()->json(['message' => 'Post not found'], Response::HTTP_NOT_FOUND);
}
$post->delete();
return response()->json(['message' => 'Post deleted'], Response::HTTP_OK);
}
}
**Connect the model to the controller is also important.
use App\Models\Post;
Step 7: Start Development Server
Start the Laravel development server Use below command
php artisan serve
Step 8: Test Using Postman
Open Postman and Create requests to test your API endpoints.
POST
http://127.0.0.1:8000/api/post
GET
http://127.0.0.1:8000/api/get
DELETE
http://127.0.0.1:8000/api/delete/6
Replace {id} with actual item IDs and adjust the JSON payloads accordingly.
Congrats! That's it! You've now built a simple Laravel backend for API integration without views. You can expand this by adding authentication, validation, and other features as needed.
Thank You.