Kimkorng

Understanding Laravel With CRUD Operations

28 JUN, 2024

Laravel is a web application framework with expressive, elegant syntax. Every feature has been thoughtfully considered to provide a wonderful developer experience. Laravel official website

Ensure you have PHP and Composer installed in your computer:

Creating Laravel Project

Create a new Laravel project:

shell
composer create-project laravel/laravel crud-app cd crud-app

Set Up Database Configuration

Configure your database connection in the .env file:

env
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your_database_name DB_USERNAME=your_database_username DB_PASSWORD=your_database_password

Run Sever

You can run your server with following command:

shell
php artisan serve

Your server might running on http://127.0.0.1:8000/.

Generate migration:

Laravel's migrations help manage database schemas.

You may use the make:migration Artisan command to generate a database migration. The new migration will be placed in your /database/migrations directory.

shell
php artisan make:migration create_posts_table

Define the posts table in the migration file yyyy_mm_dd_create_posts_table.php of /database/migrations directory.

php
public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content'); $table->timestamps(); }); }

Run the migration command to create the posts table:

shell
php artisan migrate

Generating Model Class:

You may use the make:model Artisan command to generate a new model. Models typically live in the app\Models directory.

shell
php artisan make:model Post

You need to specify which model attributes can be mass assigned. Use the $fillable property on the app\Models\Post.php to achieve this.

php
class Post extends Model { use HasFactory; protected $fillable = ['title', 'content']; }

Creating a Controller

Generate a controller to handle CRUD operations in app/Http/Controllers by using following command:

shell
php artisan make:controller PostController

Implement CRUD methods index, create, store, edit, update, destroy in PostController.php.

php
class PostController extends Controller { public function index(){ $posts = Post::all(); return view('posts.index', ['posts' => $posts]); } public function create(){ return view('posts.create'); } public function store(Request $req){ $data = $req->validate([ 'title' => 'required|max:200', 'content' => 'required' ]); $data['title'] = addslashes($data['title']); $data['content'] = addslashes($data['content']); Post::create($data); return redirect(route('posts.index')); } public function edit(Post $post){ return view('posts.edit', ['post' => $post]); } public function update(Post $post, Request $req){ $data = $req->validate([ 'title' => 'required|max:200', 'content' => 'required' ]); $data['title'] = addslashes($data['title']); $data['content'] = addslashes($data['content']); $post->update($data); return redirect(route('posts.index')); } public function destroy(Post $post){ $post->delete(); return redirect(route('posts.index')); } }

Creating Routes

Define routes for CRUD operations in routes/web.php:

php
use App\Http\Controllers\PostController; Route::get('/', [PostController::class, 'index']) -> name('post.index'); Route::get('/create', [PostController::class, 'create']) -> name('post.create'); Route::post('/store', [PostController::class, 'store']) -> name('post.store'); Route::get('/post/{post}/edit', [PostController::class, 'edit']) -> name('post.edit'); Route::put('/post/{post}/update', [PostController::class, 'update']) -> name('post.update'); Route::delete('/post/{post}', [PostController::class, 'destroy']) -> name('post.destroy');

Implement Views

Create views for posts in (resources/views/posts/).

plaintext
resources/ └── views/ └── posts/ ├── index.blade.php ├── create.blade.php └── edit.blade.php

Here are ways to display your post data as a list in user interface.

blade
// index.blade.php @foreach ($posts as $post) <h2>{{ $post->title }}</h2> <p>{{ $post->content }}</p> @endforeach

Using Laravel's form handling to create posts:

blade
// create.blade.php <form action="{{ route('posts.store') }}" method="POST"> @csrf @method('post') <input type="text" name="title"> <textarea name="content"></textarea> <button type="submit">Create Post</button> </form>

And now create a new form for handling update posts:

blade
// edit.blade.php <form action="{{ route('posts.update') }}" method="POST"> @csrf @method('put') <input type="text" name="title" value={{post->title}}> <textarea name="content">{{post->content}}</textarea> <button type="submit">Update Post</button> </form>

Thank you for reading!🐧

SHARE