Introduction
Learn how to create a Laravel 12 project using SQLite, implement the Singleton method, use interfaces, and develop a CRUD system with Blade templates.
1. Install Laravel 12
composer create-project --prefer-dist laravel/laravel myproject
2. Configure SQLite Database
Update the .env
file:
DB_CONNECTION=sqlite
DB_DATABASE=database/database.sqlite
Create the SQLite database file:
touch database/database.sqlite
3. Implement Singleton Pattern
Create a Singleton class:
namespace App\Services;
class ConfigService {
private static ?ConfigService $instance = null;
private array $config = [];
private function __construct() {}
public static function getInstance(): ConfigService {
if (self::$instance === null) {
self::$instance = new ConfigService();
}
return self::$instance;
}
public function set(string $key, $value): void {
$this->config[$key] = $value;
}
public function get(string $key) {
return $this->config[$key] ?? null;
}
}
4. Create an Interface
namespace App\Repositories;
interface PostRepositoryInterface {
public function getAll();
public function find($id);
public function create(array $data);
public function update($id, array $data);
public function delete($id);
}
5. Create CRUD Operations
Generate a model and migration:
php artisan make:model Post -m
Define fields in the migration:
schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
Run the migration:
php artisan migrate
6. Create a Repository
namespace App\Repositories;
use App\Models\Post;
class PostRepository implements PostRepositoryInterface {
public function getAll() {
return Post::all();
}
public function find($id) {
return Post::find($id);
}
public function create(array $data) {
return Post::create($data);
}
public function update($id, array $data) {
return Post::where('id', $id)->update($data);
}
public function delete($id) {
return Post::destroy($id);
}
}
7. Register the Repository
use App\Repositories\PostRepository;
use App\Repositories\PostRepositoryInterface;
public function register() {
$this->app->bind(PostRepositoryInterface::class, PostRepository::class);
}
8. Create a Controller
php artisan make:controller PostController --resource
9. Define Routes
Route::resource('/posts', PostController::class);
10. Create Blade Templates
index.blade.php:
@foreach ($posts as $post)
{{ $post->title }}
{{ $post->content }}
@endforeach
11. Run the Project
Start the Laravel server:
php artisan serve
Conclusion
With Laravel 12, SQLite, Singleton Pattern, Interfaces, and Blade templates, you can build a simple CRUD system efficiently.
0 Comments