Getting Started with Laravel on macOS: Install PHP, Composer, and Laravel to Build a CRUD Blog
Laravel is a popular PHP framework designed to make web development easier and faster by providing a clean, elegant syntax.
It follows the Model-View-Controller (MVC) architectural pattern and includes built-in tools for routing, sessions, authentication, and more, making it a great choice for both small and large web applications.
What is Composer?
Composer is a dependency management tool for PHP. It allows you to manage the libraries your project depends on and handle them automatically.
By defining the dependencies in a composer.json
file, Composer will download and update them for you, ensuring that your project has the necessary packages.
Installing Composer on macOS
- Download and Install Composer:
Open Terminal.
Verify the installation by running:
composer --version
Move Composer to a global location:
sudo mv composer.phar /usr/local/bin/composer
Run the following commands:
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
php -r "unlink('composer-setup.php');"
Setting Up Laravel on macOS
Install Homebrew (if not already installed):
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Install PHP:
brew install php
php -v
Install Composer:
If you haven't installed Composer yet, follow the steps above.
Create a New Laravel Project:
composer create-project --prefer-dist laravel/laravel my-laravel-app
cd my-laravel-app
Run the Laravel Development Server:
Open your browser and visit http://localhost:8000
to see the default Laravel welcome page.
Start the built-in Laravel development server:
php artisan serve
Building a Quick CRUD Blog with Laravel
In this tutorial, we'll create a simple CRUD (Create, Read, Update, Delete) blog application using Laravel. We'll focus on setting up the basic structure, creating posts, and managing them through a simple interface.
Step 1: Set Up the Laravel Project
Set Up the Database:
Open the .env
file in your project root.
Run Migrations:
Laravel comes with built-in migrations. To create the necessary tables, run:
php artisan migrate
Create the database in MySQL:
CREATE DATABASE blog_db;
Update the database connection settings:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog_db
DB_USERNAME=root
DB_PASSWORD=yourpassword
Create a New Laravel Project:
composer create-project --prefer-dist laravel/laravel blog-app
cd blog-app
Step 2: Create the Post Model and Migration
Define the Post Schema:
Open the generated migration file in database/migrations/xxxx_xx_xx_create_posts_table.php
.
Run the Migration:
This will create the posts
table in your database:
php artisan migrate
Update the up
method to include the necessary columns:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
Generate the Model and Migration:
php artisan make:model Post -m
Step 3: Create the Controller and Routes
Define Routes:
Open routes/web.php
and add the following:
use App\Http\Controllers\PostController;
Route::resource('posts', PostController::class);
Generate the Controller:
php artisan make:controller PostController --resource
Step 4: Implement CRUD Operations
PostController Methods:
Open app/Http/Controllers/PostController.php
.
Implement the following methods:
Destroy Method (Delete Post):
public function destroy(Post $post)
{
$post->delete();
return redirect()->route('posts.index')
->with('success', 'Post deleted successfully.');
}
Update Method (Update Post):
public function update(Request $request, Post $post)
{
$request->validate([
'title' => 'required',
'content' => 'required',
]);
$post->update($request->all());
return redirect()->route('posts.index')
->with('success', 'Post updated successfully.');
}
Edit Method (Show Edit Form):
public function edit(Post $post)
{
return view('posts.edit', compact('post'));
}
Store Method (Save Post):
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'content' => 'required',
]);
Post::create($request->all());
return redirect()->route('posts.index')
->with('success', 'Post created successfully.');
}
Create Method (Show Form):
public function create()
{
return view('posts.create');
}
Index Method (List Posts):
public function index()
{
$posts = Post::all();
return view('posts.index', compact('posts'));
}
Step 5: Create the Views
Create a Layout File:
@extends('layout')
@section('content')
<h1>Create Post</h1>
<form action="{{ route('posts.store') }}" method="POST">
@csrf
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control" required>
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea name="content" class="form-control" required></textarea>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
@endsection
- Create the Post Index View:
Create resources/views/posts/index.blade.php
:
Create resources/views/posts/create.blade.php
and edit.blade.php
similarly:
@extends('layout')
@section('content')
<h1>Posts</h1>
<a href="{{ route('posts.create') }}" class="btn btn-primary">Create Post</a>
@if ($message = Session::get('success'))
<div class="alert alert-success">{{ $message }}</div>
@endif
<table class="table">
<tr>
<th>Title</th>
<th>Content</th>
<th>Actions</th>
</tr>
@foreach ($posts as $post)
<tr>
<td>{{ $post->title }}</td>
<td>{{ $post->content }}</td>
<td>
<a href="{{ route('posts.edit', $post->id) }}" class="btn btn-warning">Edit</a>
<form action="{{ route('posts.destroy', $post->id) }}" method="POST" style="display:inline;">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
@endforeach
</table>
@endsection
Create the Post Create/Edit View:
The edit.blade.php
view is similar, but with prefilled values and an update route.
In the resources/views
directory, create a layout.blade.php
file:
<!DOCTYPE html>
<html>
<head>
<title>Laravel Blog</title>
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>
Step 6: Run the Application
Access the Blog:
Open your browser and visit http://localhost:8000/posts
to see your CRUD blog in action.
Start the Laravel Server:
php artisan serve
You've created a basic CRUD blog with Laravel, complete with the ability to create, read, update, and delete posts. You can expand on this foundation by adding more features, such as user authentication, post categories, or a commenting system.