Dev
Dev

Reputation: 1073

How import custom class in controller Laravel?

I have created a new directory Library in root of Laravel.

Inside I put the file with class:

class My { // }

So, in controller Laravel I try to get access to this class:

App\Library\My

But Laravel does not determine this path.

This is my code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use View;

use App\Library\My;

class HomeController extends Controller
{
 //
}

Upvotes: 6

Views: 28210

Answers (4)

Fellipe Sanches
Fellipe Sanches

Reputation: 8125

A complete and functional example based on the posts here:

1 - Folder and file - Create a folder under app/, in this example we will create a folder called Library.

We will also inside the folder create a file with the name of your class, here we will create a class called My.

So we will have app/Library/My.php

2 - Class and method - Now, for testing, inside the class create a static method called myMethod

<?php

namespace App\Library;

class My
{
    public static function myMethod() 
    {
        return 'it\'s work!';
    }
}

3 - Controller - Now at the beginning of the Controller, we will declare the namespace of your Class with use:

<?php

namespace App\Http\Controllers;
use App\Library\My;

//rest of the controller code

Finally, to create an instance of the My class, in Controller, a new statement must be used:

//rest of the controller code

public function index()
{ 
    $whatever = new My;
    return $whatever::myMethod();
}

Upvotes: 6

Zayn Ali
Zayn Ali

Reputation: 4915

You have to properly namespace your every class.

So you can import your class with use keyword, like so

use App\Library\My;

....

$my = new My();

Or if you've conflicting class name then you can use as keyword to alias the classname while importing

use App\Library\My as MySecond;

....

$my = new MySecond();

And if you want to directly access your class within the method then you can access it like so.

$my = new \App\Library\My();

Note: The leading \ means App was declared in the global scope.

Upvotes: 2

cp50
cp50

Reputation: 164

As above, make sure it is placed in the App directory and make sure it is properly namespaced e.g.

<?php
  $fOne = new \App\library\functions;
  $isOk = ($fOne->isOk());
?>

Upvotes: 4

Dinh Phong
Dinh Phong

Reputation: 596

You should create Library folder inside app folder

namespace App\Library\My

app folder is alrdy used psr-4

In your controller

use App\Library\My as My

It's work for me. Hope this answer is helpful

Upvotes: 2

Related Questions