LARAVEL

Laravel Basic Controller


Creating a basic controller in Laravel is straightforward. You can generate a controller using Laravel's Artisan command-line tool. Here's a step-by-step guide:

 

Step 1: Open Terminal/Command Prompt

Open your terminal or command prompt.

 

Step 2: Navigate to Your Laravel Project Directory

Use the cd command to navigate to your Laravel project directory.

cd path_to_your_laravel_project

 

Step 3: Generate the Controller

Use the make:controller Artisan command to generate a new controller. Replace ExampleController with the name you want to give to your controller.

php artisan make:controller ExampleController

This command will create a new file named ExampleController.php in the app/Http/Controllers directory of your Laravel project.

 

Step 4: Open the Controller File

Navigate to the app/Http/Controllers directory in your project and open the newly created ExampleController.php file using your preferred code editor.

 

Step 5: Define Controller Methods

Inside the ExampleController class, you can define various methods that will handle different HTTP requests and perform specific actions. Here's an example with some basic methods:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ExampleController extends Controller
{
    public function index()
    {
        // Logic for handling index page
    }

    public function show($id)
    {
        // Logic for showing a specific item
    }

    public function create()
    {
        // Logic for showing a form to create a new item
    }

    public function store(Request $request)
    {
        // Logic for storing a new item
    }

    public function edit($id)
    {
        // Logic for showing a form to edit an existing item
    }

    public function update(Request $request, $id)
    {
        // Logic for updating an existing item
    }

    public function destroy($id)
    {
        // Logic for deleting an item
    }
}

 

Step 6: Save the Controller File

Save the ExampleController.php file after defining your controller methods.

Your basic controller is now ready. You can use these methods to handle different routes and perform actions accordingly in your Laravel application. Don't forget to define routes that map to these controller methods in your routes/web.php or routes/api.php file.


LARAVEL