🇬🇧 EN | 🇷🇴 RO

PHP / Laravel / MySQL

Complete Tutorial - From Basics to Advanced (2025)

Tutorial Complet - De la Bază la Avansat (2025)

PHP 8.2+ Laravel 11 MySQL 8.0

PHP Fundamentals

Fundamentele PHP

What is PHP?

PHP (Hypertext Preprocessor) is a widely-used open-source server-side scripting language designed for web development. It powers over 77% of websites globally including WordPress, Facebook, and Wikipedia.

Why Learn PHP in 2025?

  • Market Dominance: Powers majority of websites worldwide
  • Easy to Learn: Beginner-friendly syntax
  • Database Integration: Excellent MySQL/PostgreSQL support
  • Job Opportunities: High demand for PHP developers
  • Large Community: Extensive documentation and support

Basic Syntax

<?php // Variables $name = "John Doe"; $age = 30; $price = 19.99; $isActive = true; // Output echo "Hello, " . $name; print "Age: " . $age; // Conditional Statements if ($age >= 18) { echo "Adult"; } elseif ($age >= 13) { echo "Teenager"; } else { echo "Child"; } // Loops for ($i = 0; $i < 5; $i++) { echo $i; } foreach ($array as $item) { echo $item; } // Functions function greet($name) { return "Hello, " . $name; } echo greet("World"); ?>

Object-Oriented PHP

<?php // Class Definition class User { private $name; private $email; public function __construct($name, $email) { $this->name = $name; $this->email = $email; } public function getName() { return $this->name; } public function getEmail() { return $this->email; } } // Inheritance class Admin extends User { private $role = "administrator"; public function getRole() { return $this->role; } } // Interface interface PaymentInterface { public function pay($amount); } class StripePayment implements PaymentInterface { public function pay($amount) { // Stripe implementation } } // Trait trait Loggable { public function log($message) { file_put_contents('log.txt', $message); } } class MyClass { use Loggable; } ?>

Namespaces

<?php namespace App\Controllers; use App\Models\User; use App\Services\EmailService as Mailer; class UserController { public function index() { $users = User::all(); return $users; } } ?>

Ce este PHP?

PHP (Hypertext Preprocessor) este un limbaj de scriptare server-side open-source utilizat pe scară largă pentru dezvoltare web. Alimentează peste 77% din site-urile web la nivel global, inclusiv WordPress, Facebook și Wikipedia.

De ce să învăț PHP în 2025?

  • Dominanță pe Piață: Alimentează majoritatea site-urilor web
  • Ușor de Învățat: Sintaxă prietenoasă pentru începători
  • Integrare Baze de Date: Suport excelent MySQL/PostgreSQL
  • Oportunități de Carieră: Cerere mare pentru dezvoltatori PHP
  • Comunitate Mare: Documentație extinsă și suport

Sintaxă de Bază

<?php // Variabile $nume = "Ion Popescu"; $varsta = 30; // Afișare echo "Salut, " . $nume; // Condiții if ($varsta >= 18) { echo "Adult"; } else { echo "Minor"; } // Bucle for ($i = 0; $i < 5; $i++) { echo $i; } // Funcții function saluta($nume) { return "Salut, " . $nume; } ?>

MySQL Database

Bază de Date MySQL

What is MySQL?

MySQL is the world's most popular open-source relational database management system. It uses SQL (Structured Query Language) for data management and is known for its reliability, performance, and ease of use.

MySQL Key Features:

  • Fast & Reliable: Optimized for speed and stability
  • ACID Compliant: Ensures data integrity
  • Scalable: Handles millions of records efficiently
  • Cross-Platform: Works on Windows, Linux, macOS
  • Secure: Robust authentication and encryption

Basic SQL Commands

-- Create Database CREATE DATABASE company_db; USE company_db; -- Create Table CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, password VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- Insert Data INSERT INTO users (name, email, password) VALUES ('John Doe', 'john@example.com', 'hashed_password'); -- Insert Multiple INSERT INTO users (name, email, password) VALUES ('Alice', 'alice@example.com', 'pass1'), ('Bob', 'bob@example.com', 'pass2'); -- Select Data SELECT * FROM users; SELECT name, email FROM users WHERE id = 1; SELECT * FROM users WHERE name LIKE '%John%'; SELECT * FROM users ORDER BY created_at DESC LIMIT 10; -- Update Data UPDATE users SET name = 'Jane Doe', email = 'jane@example.com' WHERE id = 1; -- Delete Data DELETE FROM users WHERE id = 1;

JOIN Operations

-- INNER JOIN (matching records only) SELECT users.name, posts.title FROM users INNER JOIN posts ON users.id = posts.user_id; -- LEFT JOIN (all from left + matches from right) SELECT users.name, COUNT(posts.id) as post_count FROM users LEFT JOIN posts ON users.id = posts.user_id GROUP BY users.id; -- RIGHT JOIN SELECT users.name, orders.total FROM users RIGHT JOIN orders ON users.id = orders.user_id; -- Multiple Joins SELECT u.name, p.title, c.content FROM users u INNER JOIN posts p ON u.id = p.user_id LEFT JOIN comments c ON p.id = c.post_id;

PHP MySQL Connection with PDO

<?php // Database Configuration $host = 'localhost'; $dbname = 'company_db'; $username = 'root'; $password = ''; try { // Create PDO Connection $pdo = new PDO( "mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ] ); // Prepared Statement (prevents SQL injection) $stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email"); $stmt->execute([':email' => $email]); $user = $stmt->fetch(); // Insert with Prepared Statement $stmt = $pdo->prepare( "INSERT INTO users (name, email, password) VALUES (:name, :email, :password)" ); $stmt->execute([ ':name' => $name, ':email' => $email, ':password' => password_hash($password, PASSWORD_BCRYPT) ]); // Get Last Insert ID $lastId = $pdo->lastInsertId(); } catch (PDOException $e) { die("Error: " . $e->getMessage()); } ?>

Ce este MySQL?

MySQL este cel mai popular sistem de management al bazelor de date relaționale open-source din lume. Folosește SQL (Structured Query Language) pentru gestionarea datelor și este cunoscut pentru fiabilitate, performanță și ușurință în utilizare.

Caracteristici Cheie MySQL:

  • Rapid & Fiabil: Optimizat pentru viteză și stabilitate
  • Conform ACID: Asigură integritatea datelor
  • Scalabil: Gestionează milioane de înregistrări eficient
  • Cross-Platform: Funcționează pe Windows, Linux, macOS
  • Securizat: Autentificare și criptare robustă

Comenzi SQL de Bază

-- Creare Bază de Date CREATE DATABASE companie_db; USE companie_db; -- Creare Tabel CREATE TABLE utilizatori ( id INT AUTO_INCREMENT PRIMARY KEY, nume VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, parola VARCHAR(255) NOT NULL ); -- Inserare Date INSERT INTO utilizatori (nume, email, parola) VALUES ('Ion Popescu', 'ion@example.com', 'parola_hash'); -- Selectare Date SELECT * FROM utilizatori; SELECT nume, email FROM utilizatori WHERE id = 1; -- Actualizare Date UPDATE utilizatori SET nume = 'Maria' WHERE id = 1; -- Ștergere Date DELETE FROM utilizatori WHERE id = 1;

HTTP Methods

Metode HTTP

Understanding HTTP Methods

HTTP methods define the action to be performed on resources. They are fundamental for RESTful API development.

1. GET Request

Characteristics:

  • Purpose: Retrieve/read data from server
  • Safe: Yes - doesn't modify server state
  • Idempotent: Yes - repeated calls have same effect
  • Cacheable: Yes
  • Parameters: Sent in URL (query string)
  • Body: No request body
GET /api/users/123 HTTP/1.1 Host: example.com Authorization: Bearer token123 // With Query Parameters GET /api/products?category=electronics&min_price=100 HTTP/1.1

2. POST Request

Characteristics:

  • Purpose: Create new resources
  • Safe: No - modifies server state
  • Idempotent: No - creates duplicates
  • Cacheable: Usually not cached
  • Parameters: Sent in request body
  • Body: Has request body with data
POST /api/users HTTP/1.1 Host: example.com Content-Type: application/json Authorization: Bearer token123 { "name": "John Doe", "email": "john@example.com", "phone": "0123456789" }

3. PUT Request

Characteristics:

  • Purpose: Update/replace existing resource
  • Safe: No - modifies server state
  • Idempotent: Yes - same result on repeat
  • Update Type: Complete replacement
  • ID in URL: Client specifies resource location
PUT /api/users/123 HTTP/1.1 Host: example.com Content-Type: application/json { "id": 123, "name": "John Updated", "email": "john.new@example.com" }

POST vs PUT - Key Differences

Aspect POST PUT
Action Create new resource Update existing resource
Idempotent ❌ No - creates duplicates ✅ Yes - same result
ID Specification Server generates Client specifies in URL
Update Type Partial update Complete replacement

4. DELETE Request

DELETE /api/users/123 HTTP/1.1 Host: example.com Authorization: Bearer token123

HTTP Status Codes

2xx Success

  • 200 OK: Request successful
  • 201 Created: Resource created
  • 204 No Content: Success, no data

4xx Client Errors

  • 400 Bad Request: Invalid data
  • 401 Unauthorized: Not authenticated
  • 404 Not Found: Resource not found

5xx Server Errors

  • 500 Internal Error: Server error
  • 503 Unavailable: Server down

Înțelegerea Metodelor HTTP

Metodele HTTP definesc acțiunea care trebuie efectuată asupra resurselor. Sunt fundamentale pentru dezvoltarea API-urilor RESTful.

1. Cerere GET

  • Scop: Citirea datelor de pe server
  • Sigură: Da - nu modifică starea serverului
  • Idempotentă: Da
  • Cache-abilă: Da

2. Cerere POST

  • Scop: Creează resurse noi
  • Sigură: Nu
  • Idempotentă: Nu

POST vs PUT

Aspect POST PUT
Acțiune Creează nou Actualizează existent
Idempotent Nu Da

Laravel Framework

Framework Laravel

What is Laravel?

Laravel is a powerful PHP web application framework with elegant syntax. It follows the MVC (Model-View-Controller) architecture and provides robust tools for routing, authentication, caching, and database management.

Why Laravel?

  • Elegant Syntax: Clean, readable code
  • MVC Architecture: Well-organized structure
  • Rich Ecosystem: Forge, Vapor, Nova, Jetstream
  • Built-in Features: Authentication, queues, events
  • Active Community: Extensive documentation

Installation Steps

Step 1: Install Composer

Download from getcomposer.org

composer --version

Step 2: Create Project

composer create-project laravel/laravel my-project

Step 3: Configure .env

Set database credentials and app settings

Step 4: Run Server

php artisan serve

Project Structure

my-project/ ├── app/ │ ├── Http/Controllers/ # Controllers │ ├── Models/ # Eloquent models │ └── Providers/ # Service providers ├── routes/ │ ├── web.php # Web routes │ └── api.php # API routes ├── database/ │ ├── migrations/ # Database migrations │ └── seeders/ # Database seeders ├── resources/ │ └── views/ # Blade templates └── .env # Environment config

Routing

// routes/web.php use Illuminate\Support\Facades\Route; // Basic route Route::get('/', function () { return view('welcome'); }); // Route with parameter Route::get('/user/{id}', function ($id) { return "User ID: " . $id; }); // Route to controller Route::get('/users', [UserController::class, 'index']); // Named route Route::get('/profile', [ProfileController::class, 'show']) ->name('profile'); // Route groups Route::prefix('admin')->middleware('auth')->group(function () { Route::get('/dashboard', [AdminController::class, 'dashboard']); });

Controllers

// Create controller php artisan make:controller UserController // app/Http/Controllers/UserController.php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; class UserController extends Controller { public function index() { $users = User::all(); return view('users.index', compact('users')); } public function store(Request $request) { $validated = $request->validate([ 'name' => 'required|max:255', 'email' => 'required|email|unique:users' ]); $user = User::create($validated); return redirect()->route('users.show', $user->id); } }

Eloquent ORM

// Create model php artisan make:model Post -m // app/Models/Post.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $fillable = ['title', 'content', 'user_id']; // Relationships public function user() { return $this->belongsTo(User::class); } public function comments() { return $this->hasMany(Comment::class); } } // Usage $posts = Post::all(); $post = Post::find(1); $posts = Post::with('user')->where('user_id', 1)->get(); // Create Post::create([ 'title' => 'My Post', 'content' => 'Content here' ]);

Migrations

// Create migration php artisan make:migration create_posts_table // Migration file public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained(); $table->string('title'); $table->text('content'); $table->timestamps(); }); } // Run migrations php artisan migrate

Blade Templates

{{-- resources/views/users/index.blade.php --}} @extends('layouts.app') @section('content') <h1>Users</h1> @foreach($users as $user) <p>{{ $user->name }}</p> @endforeach @endsection

Essential Artisan Commands

php artisan serve # Start development server php artisan migrate # Run migrations php artisan make:model User # Create model php artisan make:controller UserController php artisan make:migration create_users_table php artisan cache:clear # Clear cache php artisan config:cache # Cache config php artisan tinker # Interactive shell

Laravel Best Practices 2025

Keep Your Laravel Updated

Always use the latest stable Laravel version for:

  • Improved Security: Regular security patches and fixes
  • Better Performance: Optimized code and faster load times
  • New Features: Access to latest functionality
  • Package Compatibility: Better support for community packages

Validation Best Practices

// Form Request Validation (Recommended) php artisan make:request StoreUserRequest // app/Http/Requests/StoreUserRequest.php class StoreUserRequest extends FormRequest { public function authorize() { return true; } public function rules() { return [ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users', 'password' => 'required|min:8|confirmed', 'age' => 'required|integer|min:18' ]; } public function messages() { return [ 'email.required' => 'Email is required', 'password.min' => 'Password must be at least 8 characters' ]; } } // Use in Controller public function store(StoreUserRequest $request) { $user = User::create($request->validated()); return response()->json($user, 201); }

Single Action Controllers

Keep controllers focused and organized by using single action controllers for complex operations.

// Instead of multiple methods in one controller class UserController { public function store() { } public function update() { } public function sendEmail() { } } // Use single action controllers class StoreUserController { public function __invoke(Request $request) { // Handle user creation } } class SendUserEmailController { public function __invoke(User $user) { // Handle email sending } }

Query Optimization

Avoid N+1 Query Problem

Always use eager loading to prevent performance issues:

// BAD - N+1 Problem (100 users = 101 queries) $users = User::all(); foreach ($users as $user) { echo $user->profile->bio; } // GOOD - Eager Loading (100 users = 2 queries) $users = User::with('profile')->get(); foreach ($users as $user) { echo $user->profile->bio; } // Multiple relationships $posts = Post::with(['user', 'comments', 'tags'])->get(); // Nested relationships $users = User::with('posts.comments.author')->get();

Caching Strategies

// Cache configuration php artisan config:cache // Cache routes php artisan route:cache // Query result caching $users = Cache::remember('users', 3600, function () { return User::all(); }); // Cache tags (Redis/Memcached) Cache::tags(['users', 'premium'])->put('key', $value, 3600); Cache::tags(['users'])->flush();

Security Best Practices

Essential Security Measures:

  • Always use HTTPS in production
  • Validate all inputs with Form Requests
  • Use CSRF protection (@csrf in forms)
  • Implement rate limiting on API routes
  • Hash passwords with bcrypt/argon2
  • Never commit .env file to version control
  • Use policies for authorization
  • Enable 2FA for admin accounts

Testing in Laravel

// Feature Test php artisan make:test UserTest // tests/Feature/UserTest.php class UserTest extends TestCase { use RefreshDatabase; public function test_user_can_be_created() { $response = $this->post('/api/users', [ 'name' => 'John Doe', 'email' => 'john@example.com', 'password' => 'password123' ]); $response->assertStatus(201); $this->assertDatabaseHas('users', [ 'email' => 'john@example.com' ]); } } // Run tests php artisan test

Ce este Laravel?

Laravel este un framework PHP puternic pentru aplicații web cu sintaxă elegantă. Urmează arhitectura MVC (Model-View-Controller) și oferă instrumente robuste pentru routing, autentificare, caching și gestionarea bazelor de date.

Pași de Instalare

Pas 1: Instalare Composer

Descarcă de pe getcomposer.org

Pas 2: Creare Proiect

composer create-project laravel/laravel proiect

Pas 3: Configurare

Setează credențiale în .env

Pas 4: Pornire Server

php artisan serve

Comenzi Artisan Esențiale

php artisan serve # Pornește serverul php artisan migrate # Rulează migrări php artisan make:model Utilizator # Creează model php artisan cache:clear # Curăță cache

Advanced Topics

Subiecte Avansate

Service Container & Dependency Injection

Laravel's Service Container is a powerful tool for managing class dependencies and performing dependency injection.

// Without DI (tightly coupled) class UserController { public function store() { $mailer = new Mailer(); // Hard dependency $mailer->send('Welcome'); } } // With DI (loosely coupled) class UserController { protected $mailer; public function __construct(MailerInterface $mailer) { $this->mailer = $mailer; // Injected } public function store() { $this->mailer->send('Welcome'); } }

SOLID Principles

5 Principles for Better Code:

  • S - Single Responsibility: One class, one job
  • O - Open/Closed: Open for extension, closed for modification
  • L - Liskov Substitution: Subclasses should be replaceable
  • I - Interface Segregation: Many specific interfaces
  • D - Dependency Inversion: Depend on abstractions

Repository Pattern

// Interface interface UserRepositoryInterface { public function all(); public function find($id); public function create(array $data); } // Implementation class UserRepository implements UserRepositoryInterface { protected $model; public function __construct(User $model) { $this->model = $model; } public function all() { return $this->model->all(); } public function find($id) { return $this->model->findOrFail($id); } public function create(array $data) { return $this->model->create($data); } }

Events & Listeners

// Create event php artisan make:event UserRegistered // Create listener php artisan make:listener SendWelcomeEmail // Dispatch event event(new UserRegistered($user));

Jobs & Queues

// Create job php artisan make:job ProcessPayment // Dispatch job ProcessPayment::dispatch($order); // Dispatch with delay ProcessPayment::dispatch($order)->delay(now()->addMinutes(5)); // Run queue worker php artisan queue:work

Service Container & Dependency Injection

Service Container-ul Laravel este un instrument puternic pentru gestionarea dependențelor claselor.

Principii SOLID

  • S - Responsabilitate Unică: O clasă, un scop
  • O - Deschis/Închis: Deschis pentru extindere
  • L - Substituție Liskov: Subclasele înlocuibile
  • I - Segregare Interfețe: Interfețe specifice
  • D - Inversare Dependențe: Depinde de abstracții

Technical Interview Q&A

Întrebări și Răspunsuri Interviu

PHP Questions

Q: What are namespaces in PHP?

Answer: Namespaces organize PHP code and prevent naming conflicts. They:

  • Avoid name collisions between libraries
  • Organize code logically
  • Enable efficient autoloading (PSR-4)
  • Improve maintainability
Q: Difference between Abstract Classes and Interfaces?

Answer:

  • Abstract Class: Can have concrete methods and properties. Single inheritance only.
  • Interface: Only method signatures. Multiple implementation allowed.
Q: What are Traits?

Answer: Traits are code reuse mechanisms allowing method inclusion in multiple classes without inheritance.

MySQL Questions

Q: Types of MySQL indexes?

Answer:

  • PRIMARY: Unique identifier
  • UNIQUE: Ensures unique values
  • INDEX: Speeds up queries
  • COMPOSITE: Multiple columns
Q: Types of JOIN?

Answer: INNER JOIN (matching records), LEFT JOIN (all left + matches), RIGHT JOIN (all right + matches), CROSS JOIN (cartesian product)

Laravel Questions

Q: What is Service Container?

Answer: IoC container managing class dependencies. Benefits: loose coupling, easier testing, automatic resolution.

Q: What are Eloquent Relationships?

Answer: One-to-One (hasOne/belongsTo), One-to-Many (hasMany/belongsTo), Many-to-Many (belongsToMany), Polymorphic (morphTo/morphMany)

Q: N+1 Query Problem?

Answer: Occurs when querying model then looping for relationships. Solution: Eager loading with with()

// BAD $posts = Post::all(); foreach ($posts as $post) { echo $post->user->name; // N queries } // GOOD $posts = Post::with('user')->get(); foreach ($posts as $post) { echo $post->user->name; // 2 queries total }
Q: Laravel Performance Optimization?

Answer:

  • Eager Loading: Prevent N+1 with with()
  • Caching: Config, routes, views, queries
  • Indexing: Database indexes on frequent columns
  • Queues: Background processing
  • Redis: For caching and sessions

Security Questions

Q: Prevent SQL Injection?

Answer: Use prepared statements, PDO with parameter binding, Eloquent ORM (automatic protection), never concatenate user input.

Q: CSRF Protection?

Answer: Laravel generates unique token per session, requires @csrf in forms, auto-validates on POST/PUT/DELETE.

Întrebări PHP

Î: Ce sunt namespace-urile?

Răspuns: Organizează codul PHP și previn conflictele de nume. Permit autoloading eficient (PSR-4).

Întrebări MySQL

Î: Tipuri de JOIN?

Răspuns: INNER JOIN (potriviri), LEFT JOIN (toate din stânga), RIGHT JOIN (toate din dreapta)

Întrebări Laravel

Î: Ce este Service Container?

Răspuns: Container IoC care gestionează dependențele. Beneficii: cuplare slabă, testare ușoară.

Î: Optimizare performanță Laravel?

Răspuns: Eager Loading cu with(), Caching, Indexare bază de date, Cozi, Redis.