How to use class in controller in laravel?

Member

by samara , in category: PHP Frameworks , 11 days ago

How to use class in controller in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 10 days ago

@samara 

In Laravel, controllers are used to handle user requests and generate responses. To use a class in a controller in Laravel, you can follow these steps:

  1. Create a class in the app directory of your Laravel project. For example, you can create a Helper class:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// app/Helper.php

namespace App;

class Helper
{
    public static function formatName($name)
    {
        return ucfirst($name);
    }
}


  1. To use this Helper class in a controller, you can simply import the class at the top of the controller file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// app/Http/Controllers/ExampleController.php

namespace AppHttpControllers;

use AppHelper;
use IlluminateHttpRequest;

class ExampleController extends Controller
{
    public function example()
    {
        $name = 'john doe';

        $formattedName = Helper::formatName($name);

        return view('example', ['name' => $formattedName]);
    }
}


  1. In the above example, we import the Helper class using the use statement and then use the formatName method of the Helper class in the example method of the ExampleController.


Now you can use the Helper class in the ExampleController to perform any necessary operations. Make sure to follow the proper namespace and class naming conventions while creating and using classes in Laravel controllers.