Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and using classes in Laravel

Tags:

php

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

like image 582
Khaled Rimawi Avatar asked Jan 28 '23 10:01

Khaled Rimawi


1 Answers

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.

like image 112
Supun Praneeth Avatar answered Feb 05 '23 17:02

Supun Praneeth