6

I want to create my own class and use it inside my controller, but i don't know exactly how. I did the following:

  1. I created a php file which contains my class in a sub-folder inside the App folder. the php file (class) is called JunkFunction and the sub-folder is called myClasses.

  2. In my controller i insert this line of code on the top :

    use App\myClasses\JunkFunction;

  3. I create an object of the class as the following:

    $function = new JunkFunction;

But this exception is thrown :

Class 'App\myClasses\JunkFunction' not found in D:\graduation project\kh\app\Http\Controllers\UploadsController.php

4
  • 1
    Did you put namespace App\myClasses; in your class file? Commented Mar 23, 2018 at 16:47
  • Make sure the file is named JunkFunction.php, uses the correct namespace (namespace App\myClasses;), the class name is class JunkFunction ..., and if necessary, run composer dump-autoload Commented Mar 23, 2018 at 16:48
  • 1
    Thank you very much, i missed to put the namespace in my class file. Commented Mar 23, 2018 at 17:16
  • ya , this is namespace issue, put <code> namesapce App\myClasses </code> Commented Mar 23, 2018 at 17:21

2 Answers 2

6

There are two ways you can create a class in laravel (recommend)

1. Create a Model
This is the most recommended way to create a class in laravel. command to create a model: php artisan make:model ModelName then you can use it as a use App\ModelName;

2. As a helper
This is no recommend.This one only use when you need a function/class exist in anywhere in the project so you cannot create class/function in same names.

  • first create your class/function file and add it into the app folder.
  • Then open your composer.json file and add your file path inzide of autoload part

    "autoload": { "files": [ "app/YourFunction.php" ] }

  • then run composer dump-autoload

and you are done.

Sign up to request clarification or add additional context in comments.

Comments

4
namespace App\myClasses;

put the namespace on top of file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.