Khaled Rimawi
Khaled Rimawi

Reputation: 115

Creating and using classes in Laravel

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

Upvotes: 6

Views: 14231

Answers (2)

Supun Praneeth
Supun Praneeth

Reputation: 3160

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.

Upvotes: 6

Ravindra Bhanderi
Ravindra Bhanderi

Reputation: 2936

namespace App\myClasses;

put the namespace on top of file

Upvotes: 4

Related Questions