Search code examples
phplaravelclasslaravel-5laravel-5.5

Class path is not found in laravel


I wrote this code to seperate the class definition of "attractions" so that I could reuse it elsewhere. I will need it from multiple pages.

So the deal is that it is unable to find the part no matter what i do.

This is the definition of the class and you can also see the folder structure.

<?php 
//this Class contains all the attractions.
// It extends the place class

use DB;

class attractions{
    public $json;
    public $name='test';
    public $id;
    public $lat;
    public $lon;
    public $time;
    public $photos;

   public function __construct($id){
  }
}

trying to create an object $task of the type class

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;

class AttractionsController extends Controller{    
    public function show($id){
        $task=new attractions($id);
        return view ('pages.attraction',['name'=>$task->name]);
// This is the old one. Can remove after you succeed in the first.         
/*      return view('pages.attraction',[
        'name'=>$task->name
        ]);*/
    }
}

This is the error that pops up "Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR) Class 'App\MyClasses\attractions\attractions' not found"

I tried every possible thing with the path but this would not be acceptable..

Any help? (I know this might be a very stupid and trivial mistake!)


Solution

  • Add namespace to your file attractions.php

    <?php
    
    namespace App\MyClasses;
    
    class attractions {
        public $name = 'test';
        // other variable here ....
    
    
        public function example()
        {
            echo "example here";
        }
    
        public static function test()
        {
            echo "test here";
        }
    }
    

    now go to your terminal and type this command

    composer dump-autoload That will refresh your autoload file so that your new created attractions.php will be autoloaded as well.

    After the command finished executing, you can now use your global class like this.

        use App\MyClasses\attractions;
    
        SomeClass {
    
        function __construct()
        {
            // instance call
            $attraction = new attractions();
            $attraction->example();
    
            // or static call
    
            attractions::test();
        }
     }
    

    Hope that helps, let me know.