<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Adebayo Olukunle</title>
    <description>The latest articles on DEV Community by Adebayo Olukunle (@adebayo_olukunle_06daa4ec).</description>
    <link>https://dev.to/adebayo_olukunle_06daa4ec</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2803068%2Ff457e518-304b-441b-9557-2e1a6d6f655e.jpg</url>
      <title>DEV Community: Adebayo Olukunle</title>
      <link>https://dev.to/adebayo_olukunle_06daa4ec</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/adebayo_olukunle_06daa4ec"/>
    <language>en</language>
    <item>
      <title>Creating an API in Laravel</title>
      <dc:creator>Adebayo Olukunle</dc:creator>
      <pubDate>Sun, 02 Mar 2025 09:03:51 +0000</pubDate>
      <link>https://dev.to/adebayo_olukunle_06daa4ec/creating-an-api-in-laravel-2n6h</link>
      <guid>https://dev.to/adebayo_olukunle_06daa4ec/creating-an-api-in-laravel-2n6h</guid>
      <description>&lt;p&gt;Laravel is a powerful PHP framework that provides a robust set of tools to build APIs efficiently. In this guide, we'll walk through the process of setting up and creating a RESTful API in Laravel, covering authentication, routing, controllers, and resource management.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;PHP&lt;/li&gt;
&lt;li&gt;Composer&lt;/li&gt;
&lt;li&gt;Laravel&lt;/li&gt;
&lt;li&gt;MySQL/PostgreSQL&lt;/li&gt;
&lt;li&gt;Postman or cURL for testing&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Install Laravel&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To start, install Laravel using Composer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;composer create-project --prefer-dist laravel/laravel api_tutorial
cd api_tutorial
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Set Up Database&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Configure your &lt;code&gt;.env&lt;/code&gt; file with your database details:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myapi_db
DB_USERNAME=root
DB_PASSWORD=secret
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run migrations to set up default tables:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Create a Model and Migration&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Generate a model and migration for a sample Post resource:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:model Post -m
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Modify the generated migration file in database/migrations/:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table-&amp;gt;id();
        $table-&amp;gt;string('title');
        $table-&amp;gt;text('content');
        $table-&amp;gt;timestamps();
    });
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the migration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4: Create a Controller&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Generate a resource controller for the Post model:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:controller PostController --api
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Modify &lt;code&gt;app/Http/Controllers/PostController.php&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index()
    {
        return response()-&amp;gt;json(Post::all());
    }

    public function store(Request $request)
    {
        $post = Post::create($request-&amp;gt;all());
        return response()-&amp;gt;json($post, 201);
    }

    public function show(Post $post)
    {
        return response()-&amp;gt;json($post);
    }

    public function update(Request $request, Post $post)
    {
        $post-&amp;gt;update($request-&amp;gt;all());
        return response()-&amp;gt;json($post);
    }

    public function destroy(Post $post)
    {
        $post-&amp;gt;delete();
        return response()-&amp;gt;json(null, 204);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 5: Define API Routes&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Modify &lt;code&gt;routes/api.php&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use App\Http\Controllers\PostController;

Route::apiResource('posts', PostController::class);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 6: Test API Endpoints&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Start the Server and Use Postman or cURL to test your endpoints:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan serve
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;GET all posts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -X GET http://localhost/api/posts
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;POST a new post:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -X POST http://localhost/api/posts -d "title=New Post&amp;amp;content=This is content" -H "Content-Type: application/json"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;GET a single post:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -X GET http://localhost/api/posts/1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Update a post:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -X PUT http://localhost/api/posts/1 -d "title=Updated Post&amp;amp;content=Updated content" -H "Content-Type: application/json"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;DELETE a post:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -X DELETE http://localhost/api/posts/1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 7: Implement Authentication&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Laravel provides API authentication via Laravel Sanctum:&lt;/p&gt;

&lt;p&gt;composer require laravel/sanctum&lt;/p&gt;

&lt;p&gt;Publish Sanctum’s configuration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run migrations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ensure that Sanctum middleware is enabled in app/Http/Kernel.php:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'api' =&amp;gt; [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use HasApiTokens in &lt;code&gt;User.php&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Authentication Routes&lt;/p&gt;

&lt;p&gt;Modify &lt;code&gt;routes/api.php&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use App\Http\Controllers\AuthController;

Route::post('register', [AuthController::class, 'register']);
Route::post('login', [AuthController::class, 'login']);

Route::middleware('auth:sanctum')-&amp;gt;group(function () {
    Route::get('user', [AuthController::class, 'user']);
    Route::post('logout', [AuthController::class, 'logout']);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Authentication Controller&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create an authentication controller:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:controller AuthController
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Modify AuthController.php:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $user = User::create([
            'name' =&amp;gt; $request-&amp;gt;name,
            'email' =&amp;gt; $request-&amp;gt;email,
            'password' =&amp;gt; Hash::make($request-&amp;gt;password),
        ]);

        $token = $user-&amp;gt;createToken('auth_token')-&amp;gt;plainTextToken;
        return response()-&amp;gt;json(['token' =&amp;gt; $token], 201);
    }

    public function login(Request $request)
    {
        $user = User::where('email', $request-&amp;gt;email)-&amp;gt;first();

        if (!$user || !Hash::check($request-&amp;gt;password, $user-&amp;gt;password)) {
            return response()-&amp;gt;json(['message' =&amp;gt; 'Invalid credentials'], 401);
        }

        $token = $user-&amp;gt;createToken('auth_token')-&amp;gt;plainTextToken;
        return response()-&amp;gt;json(['token' =&amp;gt; $token]);
    }

    public function user(Request $request)
    {
        return response()-&amp;gt;json($request-&amp;gt;user());
    }

    public function logout(Request $request)
    {
        $request-&amp;gt;user()-&amp;gt;tokens()-&amp;gt;delete();
        return response()-&amp;gt;json(['message' =&amp;gt; 'Logged out']);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You've now built a secure Laravel API with authentication, CRUD operations, and routing. You can further enhance this by adding validation, pagination, and error handling to make it production-ready.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>api</category>
      <category>laravel</category>
      <category>php</category>
    </item>
    <item>
      <title>Handling Forms, Validation Rules, and Error Handling in Laravel</title>
      <dc:creator>Adebayo Olukunle</dc:creator>
      <pubDate>Sun, 02 Mar 2025 08:42:04 +0000</pubDate>
      <link>https://dev.to/adebayo_olukunle_06daa4ec/handling-forms-validation-rules-and-error-handling-in-laravel-3i1h</link>
      <guid>https://dev.to/adebayo_olukunle_06daa4ec/handling-forms-validation-rules-and-error-handling-in-laravel-3i1h</guid>
      <description>&lt;p&gt;Laravel provides a robust and elegant way to handle form submissions, validate user input, and manage error handling. This ensures data integrity, enhances user experience, and helps prevent security vulnerabilities such as SQL injection and XSS attacks. This article explores the best practices for handling forms, validation rules, and error handling in Laravel.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;1. Creating Forms in Laravel&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;In Laravel, forms are primarily handled using Blade templates with the built-in @csrf directive to protect against cross-site request forgery (CSRF) attacks.&lt;/p&gt;

&lt;p&gt;Example: Basic Form&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;form action="{{ route('store.product') }}" method="POST"&amp;gt;
    @csrf
    &amp;lt;label for="name"&amp;gt;Product Name:&amp;lt;/label&amp;gt;
    &amp;lt;input type="text" name="name" id="name" required&amp;gt;

    &amp;lt;label for="price"&amp;gt;Price:&amp;lt;/label&amp;gt;
    &amp;lt;input type="number" name="price" id="price" required&amp;gt;

    &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
&amp;lt;/form&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The @csrf directive generates a hidden token to prevent CSRF attacks.&lt;/li&gt;
&lt;li&gt;The form uses the POST method to send data to the store.product route.&lt;/li&gt;
&lt;li&gt;Required fields ensure basic validation at the HTML level.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;2. Handling Form Submissions in Controllers&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Form submissions in Laravel are typically handled in controllers. The store method processes and validates the form data.&lt;br&gt;
Example: Controller Handling&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Illuminate\Http\Request;
use App\Models\Product;

class ProductController extends Controller
{
    public function store(Request $request)
    {
        // Validate input
        $validatedData = $request-&amp;gt;validate([
            'name' =&amp;gt; 'required|string|max:255',
            'price' =&amp;gt; 'required|numeric|min:1',
        ]);

        // Store data
        Product::create($validatedData);

        // Redirect with success message
        return redirect()-&amp;gt;back()-&amp;gt;with('success', 'Product added successfully!');
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Breakdown:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The validate() method ensures the request data adheres to defined rules.&lt;/li&gt;
&lt;li&gt;If validation passes, the product is saved in the database.&lt;/li&gt;
&lt;li&gt;If validation fails, Laravel automatically redirects the user back with validation errors.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;3. Validation Rules in Laravel&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Laravel provides numerous validation rules, including:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2hnq12pfacw7h3xnzwl1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2hnq12pfacw7h3xnzwl1.png" alt="Some Laravel validation rules and description" width="800" height="257"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Example: Advanced Validation&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$request-&amp;gt;validate([
    'email' =&amp;gt; 'required|email|unique:users,email',
    'password' =&amp;gt; 'required|min:8|confirmed',
    'age' =&amp;gt; 'nullable|integer|min:18',
]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;unique:users,email&lt;/code&gt; ensures the email is unique in the users table.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;password&lt;/code&gt; uses confirmed, meaning a password_confirmation field must match.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;nullable&lt;/code&gt; allows the field to be empty without validation errors.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;4. Displaying Validation Errors&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;When validation fails, Laravel redirects back with error messages. In the Blade template, we can display these errors.&lt;/p&gt;

&lt;p&gt;Example: Displaying Errors in Blade&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@if ($errors-&amp;gt;any())
    &amp;lt;div class="alert alert-danger"&amp;gt;
        &amp;lt;ul&amp;gt;
            @foreach ($errors-&amp;gt;all() as $error)
                &amp;lt;li&amp;gt;{{ $error }}&amp;lt;/li&amp;gt;
            @endforeach
        &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
@endif
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will display errors if validation fails.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Customizing Validation Error Messages&lt;/strong&gt;&lt;br&gt;
You can customize validation error messages using the messages() method.&lt;/p&gt;

&lt;p&gt;Example: Custom Error Messages&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$request-&amp;gt;validate([
    'name' =&amp;gt; 'required|string',
    'email' =&amp;gt; 'required|email|unique:users,email',
], [
    'name.required' =&amp;gt; 'The name field is mandatory.',
    'email.unique' =&amp;gt; 'This email is already in use.',
]);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;6. Form Request Validation&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Instead of handling validation directly in controllers, Laravel provides Form Request Validation for cleaner code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Create a Form Request&lt;/strong&gt;&lt;br&gt;
Run the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:request StoreProductRequest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Define Validation Rules&lt;/strong&gt;&lt;br&gt;
Modify the generated StoreProductRequest.php file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Illuminate\Foundation\Http\FormRequest;

class StoreProductRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' =&amp;gt; 'required|string|max:255',
            'price' =&amp;gt; 'required|numeric|min:1',
        ];
    }

    public function messages()
    {
        return [
            'name.required' =&amp;gt; 'Please enter the product name.',
            'price.numeric' =&amp;gt; 'Price must be a valid number.',
        ];
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Use It in the Controller&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function store(StoreProductRequest $request)
{
    Product::create($request-&amp;gt;validated());
    return redirect()-&amp;gt;back()-&amp;gt;with('success', 'Product added successfully!');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using Form Request Validation keeps controllers clean and ensures separation of concerns.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;7. Error Handling in Laravel&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Laravel provides robust error handling through try-catch blocks and custom error pages.&lt;/p&gt;

&lt;p&gt;Example: Handling Exceptions in Controllers&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Exception;
use Illuminate\Database\QueryException;

public function store(StoreProductRequest $request)
{
    try {
        Product::create($request-&amp;gt;validated());
        return redirect()-&amp;gt;back()-&amp;gt;with('success', 'Product added successfully!');
    } catch (QueryException $e) {
        return redirect()-&amp;gt;back()-&amp;gt;with('error', 'Database error: ' . $e-&amp;gt;getMessage());
    } catch (Exception $e) {
        return redirect()-&amp;gt;back()-&amp;gt;with('error', 'An unexpected error occurred.');
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;8. Custom Error Pages&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;You can customize error pages by modifying the resources/views/errors directory.&lt;/p&gt;

&lt;p&gt;Example: Custom 404 Page&lt;br&gt;
Create a file: resources/views/errors/404.blade.php&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@extends('layouts.app')

@section('content')
    &amp;lt;h1&amp;gt;Page Not Found&amp;lt;/h1&amp;gt;
    &amp;lt;p&amp;gt;Sorry, the page you are looking for does not exist.&amp;lt;/p&amp;gt;
    &amp;lt;a href="{{ url('/') }}"&amp;gt;Return Home&amp;lt;/a&amp;gt;
@endsection
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Handling forms, validation, and error handling in Laravel is straightforward and powerful. By utilizing built-in validation rules, form request validation, and error handling mechanisms, developers can create secure and user-friendly applications.&lt;/p&gt;

&lt;p&gt;Key Takeaways:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use Laravel’s validate() method for quick validation.&lt;/li&gt;
&lt;li&gt;Use Form Request Validation for cleaner controllers.&lt;/li&gt;
&lt;li&gt;Display validation errors properly in Blade views.&lt;/li&gt;
&lt;li&gt;Implement try-catch blocks for robust error handling.&lt;/li&gt;
&lt;li&gt;Customize error pages for a better user experience.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By following these best practices, you can efficiently handle form submissions and ensure your Laravel applications remain secure and user-friendly.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>laravel</category>
      <category>php</category>
    </item>
    <item>
      <title>Eloquent ORM (Models, Relationships) in Laravel</title>
      <dc:creator>Adebayo Olukunle</dc:creator>
      <pubDate>Sun, 02 Feb 2025 13:39:16 +0000</pubDate>
      <link>https://dev.to/adebayo_olukunle_06daa4ec/eloquent-orm-models-relationships-in-laravel-bnm</link>
      <guid>https://dev.to/adebayo_olukunle_06daa4ec/eloquent-orm-models-relationships-in-laravel-bnm</guid>
      <description>&lt;p&gt;Eloquent is Laravel's built-in ORM (Object-Relational Mapper) that provides a simple and expressive way to interact with a database. It follows the Active Record pattern, where each model corresponds to a database table, and each instance of a model represents a single row in that table.&lt;/p&gt;

&lt;p&gt;This article covers the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Creating and using Eloquent models&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Defining and using relationships (One-to-One, One-to-Many, Many-to-Many, Has-One-Through, Has-Many-Through, and Polymorphic Relationships)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Querying related data&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Best practices&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  1. Creating and Using Eloquent Models
&lt;/h2&gt;

&lt;p&gt;To create a new model in Laravel, use the Artisan command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:model Product
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command creates a Product.php file inside the app/Models directory (Laravel 8+). If using Laravel 7 or earlier, it will be in app/.&lt;/p&gt;

&lt;p&gt;A typical Eloquent model looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'price', 'description'];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Basic CRUD Operations&lt;/strong&gt;&lt;br&gt;
When a model is created as described above, it can be used to handle basic operations in your application which we often term as CRUD meaning Create a record, Retrieving records, Updating a record, and Deleting a record. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Creating a Record
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$product = Product::create([
    'name' =&amp;gt; 'Laptop',
    'price' =&amp;gt; 1500,
    'description' =&amp;gt; 'High-performance laptop'
]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;Retrieving Records
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$products = Product::all(); // Get all products
$product = Product::find(1); // Find by ID, it is usually one record
$product = Product::where('name', 'Laptop')-&amp;gt;first();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;Updating a Record
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$product = Product::find(1);
$product-&amp;gt;price = 1700;
$product-&amp;gt;save();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;Deleting a Record
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$product-&amp;gt;delete();
Product::destroy(1); // Delete by ID
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  2. Defining and Using Relationships
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;One-to-One Relationship&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this relationship, one entity is directly related to another entity. Entity in this case, an entity is a model record, say a User record would have a one-to-one-relationship with a Profile model record.&lt;/p&gt;

&lt;p&gt;Example: User and Profile&lt;/p&gt;

&lt;p&gt;&lt;code&gt;app/Models/User.php&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User extends Model
{
    public function profile()
    {
        return $this-&amp;gt;hasOne(Profile::class);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;app/Models/Profile.php&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Profile extends Model
{
    public function user()
    {
        return $this-&amp;gt;belongsTo(User::class);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fetching user profile: &lt;br&gt;
To retrieve a user record, include the following code in one of the methods in the controller class created to handle user modules which typical should be created in &lt;code&gt;app/Http/Controller/UserController.php&lt;/code&gt;, although it can be used in any class method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:controller UserController
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;open the file created in &lt;code&gt;app/Http/Controller/UserController.php&lt;/code&gt;, add the following code. you can change the method name to what you prefer, but use a name that clearly describes what the method does.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function findUserProfile() 
{
   $user = User::find(1); // 1 is the user ID
   $profile = $user-&amp;gt;profile;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;One-to-Many Relationship&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this relationship, one entity is related to multiple entities. Meaning, for instance, a specific post in the Post model would have or own multiple comments in the Comment Model (remember that a model is attached to a single Database table).&lt;/p&gt;

&lt;p&gt;Example: Post and Comments&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Post extends Model
{
    public function comments()
    {
        return $this-&amp;gt;hasMany(Comment::class);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Comment extends Model
{
    public function post()
    {
        return $this-&amp;gt;belongsTo(Post::class);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fetching comments for a post: To retrieve comment records for a specific post, include the following code in one of the methods in the controller class which should be created to handle Post modules typical as &lt;code&gt;app/Http/Controller/PostController.php&lt;/code&gt;, although it can be used in any class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:controller PostController
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;open the file created in &lt;code&gt;app/Http/Controller/UserController.php&lt;/code&gt;, add the following code. you can change the method name to what you prefer, but use a name that clearly describes what the method does.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function findPostComment() 
{
   $post = Post::find(1); // 1 is the post ID
   $comments = $post-&amp;gt;comments;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Many-to-Many Relationship&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Many entities are related to many other entities. A user can have many roles and a role can be assigned to many users. For instance, a user can have both Admin role and and HR role.&lt;/p&gt;

&lt;p&gt;Example: Users and Roles&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User extends Model
{
    // other methods can be at the top or below

    public function roles()
    {
        return $this-&amp;gt;belongsToMany(Role::class);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Role extends Model
{
    public function users()
    {
        return $this-&amp;gt;belongsToMany(User::class);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Assigning a role to a user: in your controller method, you can assign a role to a user like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// assign a role using role Id to a user
$user-&amp;gt;roles()-&amp;gt;attach($roleId);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Has-One-Through Relationship&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A relationship between two models through an intermediate model. This is useful when you need to access a related model that is connected through another model.&lt;/p&gt;

&lt;p&gt;Example: Mechanic → Car → Owner&lt;/p&gt;

&lt;p&gt;In this scenario, a mechanic services a car, and each car has one owner. Instead of defining two separate relationships, we can use a has-one-through relationship to access the owner directly from the mechanic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Mechanic extends Model
{
    public function owner()
    {
        return $this-&amp;gt;hasOneThrough(Owner::class, Car::class);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This allows you to fetch an owner directly from a mechanic:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$mechanic = Mechanic::find(1);
$owner = $mechanic-&amp;gt;owner;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Has-Many-Through Relationship&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A single model has many related models through an intermediate model. This is useful when a model is indirectly related to another model.&lt;/p&gt;

&lt;p&gt;Example: Country → Users → Posts&lt;/p&gt;

&lt;p&gt;A country has many users, and each user has many posts. Instead of fetching users first and then fetching their posts, we can define a has-many-through relationship.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Country extends Model
{
    public function posts()
    {
        return $this-&amp;gt;hasManyThrough(Post::class, User::class);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fetching posts from a country directly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$country = Country::find(1);
$posts = $country-&amp;gt;posts;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Polymorphic Relationships&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Allows multiple models to share the same relationship, meaning different models can be associated with a single model type.&lt;/p&gt;

&lt;p&gt;Example: Comments on Posts and Videos&lt;/p&gt;

&lt;p&gt;Both posts and videos can have comments, so we use a polymorphic relationship.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Comment extends Model
{
    public function commentable()
    {
        return $this-&amp;gt;morphTo();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Post extends Model
{
    public function comments()
    {
        return $this-&amp;gt;morphMany(Comment::class, 'commentable');
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Video extends Model
{
    public function comments()
    {
        return $this-&amp;gt;morphMany(Comment::class, 'commentable');
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This allows us to fetch comments on a post or video:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$post = Post::find(1);
$comments = $post-&amp;gt;comments;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$video = Video::find(1);
$comments = $video-&amp;gt;comments;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Saving a polymorphic comment:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$post-&amp;gt;comments()-&amp;gt;create(['body' =&amp;gt; 'Great post!']);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Querying Related Data
&lt;/h2&gt;

&lt;p&gt;Eloquent provides powerful methods to retrieve related data efficiently.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Eager Loading&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Preload related data to optimize queries.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$users = User::with('profile')-&amp;gt;get();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Lazy Loading&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Loads related data only when accessed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$user = User::find(1);
$profile = $user-&amp;gt;profile;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Constraining Eager Loading&lt;/strong&gt;&lt;br&gt;
You are able to give a condition to what relationship you want to be eager loaded on your model.&lt;/p&gt;

&lt;p&gt;$users = User::with(['posts' =&amp;gt; function ($query) {&lt;br&gt;
    $query-&amp;gt;where('status', 'published');&lt;br&gt;
}])-&amp;gt;get();&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Best Practices
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Use fillable or guarded to prevent mass assignment vulnerabilities.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use eager loading to optimize database queries and reduce N+1 query issues.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Follow naming conventions. Eloquent assumes table names and foreign keys based on model names. table name should be plural, model name should singular, foreign fields are in snake case, like &lt;code&gt;user_id&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use relationships instead of raw joins for cleaner and maintainable code.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Eloquent ORM in Laravel simplifies database interactions by providing an intuitive syntax for working with models and relationships. Mastering Eloquent will help you write efficient, maintainable, and scalable Laravel applications.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Laravel File Structure and MVC Architecture</title>
      <dc:creator>Adebayo Olukunle</dc:creator>
      <pubDate>Sun, 02 Feb 2025 11:35:14 +0000</pubDate>
      <link>https://dev.to/adebayo_olukunle_06daa4ec/laravel-file-structure-and-mvc-architecture-32lg</link>
      <guid>https://dev.to/adebayo_olukunle_06daa4ec/laravel-file-structure-and-mvc-architecture-32lg</guid>
      <description>&lt;p&gt;Laravel is one of the most popular PHP frameworks, known for its elegant syntax and robust features. It follows the Model-View-Controller (MVC) architecture, which helps developers organize code efficiently. Understanding Laravel’s file structure is crucial for developing scalable applications. In this article, we’ll explore Laravel’s directory structure and its implementation of the MVC architecture.&lt;/p&gt;

&lt;h2&gt;
  
  
  Laravel File Structure
&lt;/h2&gt;

&lt;p&gt;When you install Laravel, the framework creates a structured directory layout. Below is an overview of the key directories and files in a Laravel project:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Root Directory&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;app/:&lt;/strong&gt; Contains the core application logic, including Models, Controllers, and Middleware.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;bootstrap/:&lt;/strong&gt; Stores files required for the initial framework bootstrapping, including the &lt;code&gt;cache&lt;/code&gt; directory for optimized application performance.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;config/:&lt;/strong&gt; Contains configuration files for services like database connections, authentication, mail, and more.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;database/:&lt;/strong&gt; Includes database migrations, seeders, and factories.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;public/:&lt;/strong&gt; The entry point of the application (&lt;code&gt;index.php&lt;/code&gt;). Also stores assets like CSS, JavaScript, and images.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;resources/:&lt;/strong&gt; Contains view templates, raw assets, and language files.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;routes/:&lt;/strong&gt; Defines application routes (web, API, console, and channels).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;storage/:&lt;/strong&gt; Stores logs, session files, compiled views, and cache files.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;tests/:&lt;/strong&gt; Holds unit and feature tests.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;vendor/:&lt;/strong&gt; Contains third-party dependencies managed by Composer.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;1. Key Files&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;- artisan:&lt;/strong&gt; Laravel’s command-line interface for executing tasks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;- composer.json:&lt;/strong&gt; Defines dependencies for the application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;- .env: Stores&lt;/strong&gt; environment-specific configuration variables.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;- server.php:&lt;/strong&gt; Allows the application to be run using PHP’s built-in server.&lt;/p&gt;

&lt;h2&gt;
  
  
  Laravel's MVC Architecture
&lt;/h2&gt;

&lt;p&gt;Laravel follows the MVC architecture pattern, which separates the application into three main components which are Model, View, Controller. This means that when the request gets into the application route, the route passes it to the Controller, the controller accesses the Model which is the data layer, and then the Controller also passes the data from the Model to the View for the users.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Model (app/Models/)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The Model represents the data structure and business logic. It interacts with the database using Eloquent ORM (Object-Relational Mapping).&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['name', 'price', 'description'];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Object-relational mapping (ORM) is a technique that enables data to be easily mapped between a relational database management system (RDBMS) like MySQL database, and an object-oriented programming (OOP) language. ORM systems serve as a bridge between the two different paradigms.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. View (resources/views/)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Views handle the presentation layer of the application. Laravel uses Blade templating engine to create dynamic content.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Product List&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;h1&amp;gt;Products&amp;lt;/h1&amp;gt;
    &amp;lt;ul&amp;gt;
        @foreach ($products as $product)
            &amp;lt;li&amp;gt;{{ $product-&amp;gt;name }} - ${{ $product-&amp;gt;price }}&amp;lt;/li&amp;gt;
        @endforeach
    &amp;lt;/ul&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Controller (app/Http/Controllers/)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Controllers handle the application logic and bridge the Model and View.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index()
    {
        $products = Product::all();
        return view('products.index', compact('products'));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Routes (routes/web.php)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Routes define how the application responds to user requests. It follows the http verb methods to receive the request, and maps the controller class and methods which would handle the request.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use App\Http\Controllers\ProductController;

Route::get('/products', [ProductController::class, 'index']);

Route::post('/products', [ProductController::class, 'create']);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Understanding Laravel’s file structure and MVC architecture is essential for building efficient applications. The framework's well-organized directory structure and adherence to MVC principles make development streamlined and maintainable. By leveraging Models, Views, and Controllers effectively, developers can create scalable web applications with Laravel.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Database Migrations in Laravel</title>
      <dc:creator>Adebayo Olukunle</dc:creator>
      <pubDate>Sun, 02 Feb 2025 01:26:14 +0000</pubDate>
      <link>https://dev.to/adebayo_olukunle_06daa4ec/database-migrations-in-laravel-4nib</link>
      <guid>https://dev.to/adebayo_olukunle_06daa4ec/database-migrations-in-laravel-4nib</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Laravel is a popular PHP framework known for its elegant syntax and robust features. One of its most powerful features is its database management system, which includes query builders, Eloquent ORM, and migrations. Migrations allow developers to version-control their database schema, making it easy to collaborate with teams and maintain databases in different environments.&lt;/p&gt;

&lt;p&gt;In this article, we will explore databases in Laravel, focusing on database configurations, migrations, database factory seeding, and other best practices.&lt;/p&gt;

&lt;h2&gt;
  
  
  Database Configuration
&lt;/h2&gt;

&lt;p&gt;Before using Laravel's database features, you need to configure your database connection. The configuration file for databases is located in config/database.php. Laravel supports multiple database connections, including MySQL, PostgreSQL, SQLite, and SQL Server.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting Up the .env File
&lt;/h2&gt;

&lt;p&gt;Laravel uses an environment file (.env) to store sensitive database credentials. You can set up your database connection by modifying the .env file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After updating the .env file, you should run the following command to clear the configuration cache:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan config:clear
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Understanding Migrations
&lt;/h2&gt;

&lt;p&gt;Migrations in Laravel provide a version control system for your database schema, allowing you to define and modify tables using PHP instead of raw SQL. This makes database management more structured and easier to track changes across teams, as developers on your project can easily see the history of modifications that was made on your database structure.&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating Migrations
&lt;/h2&gt;

&lt;p&gt;To create a migration, use the Artisan command. Let us say you would like to create a database table called "products" which holds details about products in your application. your artisan command would be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:migration create_products_table
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will generate a migration file inside the database/migrations directory, which looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table-&amp;gt;id();
            $table-&amp;gt;timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You will find two methods in the migration class created above; the 'up' and 'down' methods. The 'up' method creates the table structure into the database using the name (in this case, 'products') which falls in between the 'create' and 'table' keywords in in the previous command above. The down method on the other hand is used to tear down the table structure when specified in the artisan command.  Before you proceed to execute the command which would run the migration, you can modify the 'up' method to include all the fields, their data types, default values, position, and other structure that is required for the products table in your application.&lt;/p&gt;

&lt;p&gt;use Illuminate\Database\Migrations\Migration;&lt;br&gt;
use Illuminate\Database\Schema\Blueprint;&lt;br&gt;
use Illuminate\Support\Facades\Schema;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table-&amp;gt;id();
            $table-&amp;gt;string('name');
            $table-&amp;gt;text('description')-&amp;gt;nullable();
            $table-&amp;gt;decimal('price', 8, 2);
            $table-&amp;gt;boolean('is_published')-&amp;gt;default(false);
            $table-&amp;gt;timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Running Migrations
&lt;/h2&gt;

&lt;p&gt;Once the migration file is created, apply it using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command executes all pending migrations, creating or modifying tables as defined in the migration files.&lt;/p&gt;

&lt;h2&gt;
  
  
  Rolling Back Migrations
&lt;/h2&gt;

&lt;p&gt;If you need to undo the last migration, use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan migrate:rollback
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  To reset the entire database schema and re-run all migrations:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan migrate:reset
php artisan migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  To rollback and re-run migrations in a single step:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan migrate:refresh
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Seeding the Database
&lt;/h2&gt;

&lt;p&gt;Laravel also provides a feature called database seeding, which allows you to insert dummy data into the database for testing and development. Seeder files are located in database/seeders.&lt;/p&gt;

&lt;p&gt;To create a seeder:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:seeder ProductSeeder
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  A typical seeder file looks like this:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class ProductSeeder extends Seeder
{
    public function run()
    {
        DB::table('products')-&amp;gt;insert([
            'name' =&amp;gt; 'Sample Product',
            'description' =&amp;gt; 'This is a sample product.',
            'price' =&amp;gt; 100.00,
            'created_at' =&amp;gt; now(),
            'updated_at' =&amp;gt; now(),
        ]);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Run the seeder using:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan db:seed --class=ProductSeeder
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  To run all seeders defined in DatabaseSeeder.php, use:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan db:seed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Factories and Seeders for Testing
&lt;/h2&gt;

&lt;p&gt;Laravel provides model factories that allow you to generate fake data using the Faker library. First, create a factory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:factory ProductFactory --model=Product
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Modify the factory file:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Product;

class ProductFactory extends Factory
{
    protected $model = Product::class;

    public function definition()
    {
        return [
            'name' =&amp;gt; $this-&amp;gt;faker-&amp;gt;word,
            'description' =&amp;gt; $this-&amp;gt;faker-&amp;gt;sentence,
            'price' =&amp;gt; $this-&amp;gt;faker-&amp;gt;randomFloat(2, 10, 500),
        ];
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Use the factory in the seeder:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use App\Models\Product;
//...
public function run(): void
{
   Product::factory()-&amp;gt;count(50)-&amp;gt;create();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Run the seeder:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan db:seed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Best Practices
&lt;/h2&gt;

&lt;p&gt;Use Descriptive Migration Names – Always name migrations clearly (e.g., create_orders_table instead of new_table).&lt;/p&gt;

&lt;p&gt;Keep Migrations Modular – Avoid modifying multiple tables in a single migration file.&lt;/p&gt;

&lt;p&gt;Use Factories for Testing – Generate dummy data efficiently using factories instead of manually inserting records.&lt;/p&gt;

&lt;p&gt;Backup Before Migration – Before running destructive commands like migrate:reset, ensure you have a backup of your database.&lt;/p&gt;

&lt;p&gt;Run Migrations in CI/CD Pipelines – Automate migrations using CI/CD workflows to keep environments synchronized.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Laravel's database management system, powered by migrations, seeders, and factories, provides a structured and maintainable way to handle databases. By leveraging migrations, you can track schema changes effectively, ensuring smooth collaboration across development teams. Understanding and implementing Laravel migrations properly will greatly enhance the efficiency and scalability of your applications.&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>php</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
