Getting Started with Laravel : Laravel Form Processing: Handling User Input and Persisting Data
Getting Started with Laravel: Handling User Input and Persisting Data
Laravel is a powerful PHP framework that simplifies common tasks in web development, making it an excellent choice for both beginners and seasoned developers. In this blog post, we’ll explore how to handle user input through forms in Laravel and persist that data in a database. This tutorial is inspired by the YouTube video “Getting Started with Laravel: Laravel Form Processing”.
Prerequisites
Before we dive into the code, ensure you have the following set up:
- PHP installed (version 7.3 or higher)
- Composer installed
- A working installation of Laravel
- A database (like MySQL) set up and configured
Setting Up Your Laravel Project
To begin, if you haven't already created a Laravel project, you can do so with the following command:
composer create-project --prefer-dist laravel/laravel my-laravel-app
Navigate to your project directory:
cd my-laravel-app
Configuring the Database
Open your .env file and configure your database settings:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password
Creating a Model and Migration
Next, we need to create a model and a migration file for the data we want to handle. For this example, let’s create a simple Post model.
Run the following command:
php artisan make:model Post -m
This command creates a Post.php model in the app/Models directory and a migration file in the database/migrations directory. Open the migration file and define the table structure. For example:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
Run the migration to create the table in your database:
php artisan migrate
Building the Form
Now, let’s create a form to collect user input. Create a new Blade view file in resources/views called create.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Post</title>
</head>
<body>
<h1>Create a Post</h1>
<form action="{{ route('posts.store') }}" method="POST">
@csrf
<label for="title">Title:</label>
<input type="text" id="title" name="title" required>
<br>
<label for="content">Content:</label>
<textarea id="content" name="content" required></textarea>
<br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Route Definition
Next, we need to define routes to handle the form display and submission. Open the routes/web.php file and add the following:
use App\Http\Controllers\PostController;
Route::get('/posts/create', [PostController::class, 'create'])->name('posts.create');
Route::post('/posts', [PostController::class, 'store'])->name('posts.store');
Creating the Controller
Now, let's create a controller to handle the form logic. Run this command to create a PostController:
php artisan make:controller PostController
Open PostController.php and add the following methods:
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function create()
{
return view('create');
}
public function store(Request $request)
{
$request->validate([
'title' => 'required|max:255',
'content' => 'required',
]);
Post::create($request->all());
return redirect()->back()->with('success', 'Post created successfully!');
}
}
Validating User Input
In the store method, we use the validate function to ensure that the incoming data is correct before saving it to the database. This validation checks that the title is required and does not exceed 255 characters, while content must also be required.
Persisting Data
The line Post::create($request->all()); handles the data persistence. It saves the validated data into the posts table.
Testing the Application
Finally, start the Laravel development server:
php artisan serve
Visit http://127.0.0.1:8000/posts/create in your web browser. Fill out the form, and upon submission, you should see a success message indicating that your post has been created.
Conclusion
In this tutorial, we have covered the essential steps to handle user input with forms in Laravel and persist that data to a database. With Laravel's built-in features, managing user input and data storage becomes significantly easier.
Feel free to explore further by adding features such as input validation feedback, updating posts, and listing all posts. Happy coding!
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment