Laravel Essentials

A simplified but comprehensive guide to Laravel

What is Laravel?

Laravel is an elegant PHP framework designed for web developers who need a simple, elegant toolkit to create full-featured web applications. It follows the MVC pattern and provides a clean, expressive syntax.

🚀

Expressive

Clean, readable code syntax

⚙️

Powerful

Advanced tools and features

🛡️

Secure

Built-in security features

Requirements

Before installing Laravel, make sure your environment meets these requirements:

  • PHP >= 8.0
  • Composer
  • Web Server (Apache/Nginx)
  • Database (MySQL/PostgreSQL)
  • Node.js & NPM (for frontend)
Tip: Make sure your PHP installation has the following extensions: BCMath, Ctype, Fileinfo, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML.

Installation

Step-by-Step Guide

  1. Create a new Laravel project

    composer create-project laravel/laravel myproject
  2. Navigate to your project directory

    cd myproject
  3. Start the development server

    php artisan serve
  4. Configure your database in .env file

    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=laravel
    DB_USERNAME=root
    DB_PASSWORD=
  5. Run migrations

    php artisan migrate

Project Structure

  • app/
    • Http/ (Controllers, Middleware)
    • Models/ (Eloquent Models)
    • Providers/ (Service Providers)
  • config/
    • Configuration files
  • database/
    • migrations/ (Database migrations)
    • seeders/ (Database seeders)
  • public/
    • Assets and entry point
  • resources/
    • views/ (Blade templates)
    • css/ (Stylesheets)
    • js/ (JavaScript files)
  • routes/
    • Application routes
  • storage/
    • Logs, cache, uploads

Routing

Routes in Laravel are defined in the routes/web.php file for web routes and routes/api.php for API routes.

// Simple route with closure
Route::get('/', function () {
    return view('welcome');
});

// Route with parameters
Route::get('/user/{id}', function ($id) {
    return 'User ID: ' . $id;
});
use App\Http\Controllers\UserController;

// Single action
Route::get('/users', [UserController::class, 'index']);

// Resource controller (CRUD)
Route::resource('products', ProductController::class);
// Group with middleware and prefix
Route::middleware(['auth'])->prefix('admin')->group(function () {
    Route::get('/dashboard', [AdminController::class, 'dashboard']);
    Route::resource('products', ProductController::class);
});
Tip: Use php artisan route:list to see all registered routes in your application.

Database Migrations

Migrations are like version control for your database schema. They allow you to define and share the application's database schema definition.

Creating Migrations

php artisan make:migration create_products_table

Migration Structure

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

class CreateProductsTable extends Migration
{
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('description')->nullable();
            $table->decimal('price', 10, 2);
            $table->integer('stock');
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Running Migrations

php artisan migrate
Run all pending migrations
php artisan migrate:rollback
Rollback the last batch of migrations
php artisan migrate:fresh
Drop all tables and re-run all migrations

CRUD Operations

Here's a simplified example of implementing CRUD (Create, Read, Update, Delete) operations in Laravel:

1. Create Model & Migration
php artisan make:model Product -m
2. Create Controller
php artisan make:controller ProductController --resource
3. Define Routes
// In routes/web.php
Route::resource('products', ProductController::class);
4. Controller Methods
// Index - Show all products
public function index()
{
    $products = Product::latest()->paginate(10);
    return view('products.index', compact('products'));
}

// Create - Show create form
public function create()
{
    return view('products.create');
}

// Store - Save new product
public function store(Request $request)
{
    $validated = $request->validate([
        'name' => 'required|string|max:255',
        'price' => 'required|numeric|min:0',
        'stock' => 'required|integer|min:0',
    ]);
    
    Product::create($validated);
    
    return redirect()->route('products.index')
        ->with('success', 'Product created successfully');
}

// Show - Display a product
public function show(Product $product)
{
    return view('products.show', compact('product'));
}

// Edit - Show edit form
public function edit(Product $product)
{
    return view('products.edit', compact('product'));
}

// Update - Save changes
public function update(Request $request, Product $product)
{
    $validated = $request->validate([
        'name' => 'required|string|max:255',
        'price' => 'required|numeric|min:0',
        'stock' => 'required|integer|min:0',
    ]);
    
    $product->update($validated);
    
    return redirect()->route('products.index')
        ->with('success', 'Product updated successfully');
}

// Destroy - Delete a product
public function destroy(Product $product)
{
    $product->delete();
    
    return redirect()->route('products.index')
        ->with('success', 'Product deleted successfully');
}

Deployment

When deploying Laravel to production, follow these steps:

1

Server Setup

Set up a server with PHP 8.0+, a web server (Apache/Nginx), and database.

2

Upload Code

Use Git or FTP to upload your Laravel application to the server.

3

Environment Configuration

Set up your .env file with production settings.

APP_ENV=production
APP_DEBUG=false
4

Install Dependencies

Run composer install with optimizations.

composer install --optimize-autoloader --no-dev
5

Optimize

Run Laravel's optimization commands.

php artisan config:cache
php artisan route:cache
php artisan view:cache
6

Permissions

Set correct permissions for storage and cache directories.

chmod -R 775 storage bootstrap/cache
Important: Always make a backup of your database and files before deploying to production.