Search code examples
phplaravelmodel-view-controllerlaravel-5models

How can I correctly setup models in Laravel 5 and fix my error?


I am currently learning Laravel 5. I have connected my database. Setup routes, created a controller, created a view and attempted a model, which is where I need help.

I used php artisan to create my model, which is in the /app directory.

When I try to visit /myer on the browser. I am getting the following error:

FatalErrorException in MyersController.php line 20: Class 'App\Http\Controllers\Myer' not found

I have put the edited files on http://www.filedropper.com/help

I have no idea where I have gone wrong, I have messed around using "use" and ultimately all I get is that the Class can't be found. This is beginning to destroy my soul. If someone can help me, I would be forever grateful!!

Files

From MyersController.php

public function index()
{
    $myers = Myer::all();
    return view('myers.index')->with('myers'.$myers);
}

From routes.php

Route::get('/myer/', 'MyersController@index');

Route::resource('myer','MyersController');

From Myer.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Myer extends Model
{
//
}

From index.blade.php

   <h2>Myers</h2>
   <ul>
    @foreach ($myers as $list)
     <li>{{{ $list->name }}}</li>
    @endforeach

  </ul>

Solution

  • As you can see in the error, it tries to find the model in the same namespace as your controller: FatalErrorException in MyersController.php line 20: Class 'App\Http\Controllers\Myer' not found. In the Model, you can see it's in namespace App.

    So either put

    use App\Myer;
    

    in the top of your controller under the namespace, or reference the full path where you need it:

    public function index()
    {
        $myers = App\Myer::all();
        return view('myers.index')->with('myers'.$myers);
    }
    

    But if you will use it more often in this controller, then it's more efficient to put it in the use.

    P.S. Please don't let it destroy your soul.