Avi
Avi

Reputation: 798

How do I call a model in Laravel 5?

I'm trying to get the hang of Laravel 5 and have a question which is probably very simple to solve but I'm struggling.

I have a controller named TestController and it resides in \app\Http\Controllers

This is the controller:

<?php 
namespace App\Http\Controllers;

class TestController extends Controller {

    public function test()
    {

    $diamonds = diamonds::find(1);
    var_dump($diamonds);
    }



}

Then I have a model I created that resides in /app:

<?php

namespace App;


class diamonds extends Model {


}

Put all other mistakes aside which I'm sure there are, my problem is that laravel throws an error:

FatalErrorException in TestController.php line 10: Class 'App\Http\Controllers\diamonds' not found

So, how do I get the controller to understand I'm pointing to a model and not to a controller?

Thanks in advance...

Upvotes: 6

Views: 25862

Answers (4)

wiesson
wiesson

Reputation: 6822

You have to import your model in the Controller by using namespaces.

E.g.

use App\Customer;

class DashboardController extends Controller {
    public function index() {
        $customers = Customer::all();
        return view('my/customer/template')->with('customers', $customers);
    }
}

In your case, you could use the model directly App\diamonds::find(1); or import it first with use App\diamonds; and use it like you already did.

Further, it is recommended to use UpperCamelCase class names. So Diamonds instead of diamonds. You also could use dd() (dump and die) instead of var_dump to see a nicely formatted dump of your variable.

Upvotes: 6

Avi
Avi

Reputation: 798

Ultimately, there were a few issues here and all of you helped, however I was missing the following on the model page:

use Illuminate\Database\Eloquent\Model;

Upvotes: 0

Raheel
Raheel

Reputation: 9024

  //Your model file
  <?php
    namespace App\Models;


    class diamonds extends Model {


    }

  // And in your controller
  <?php 
    namespace App\Http\Controllers;

    use App\Models\

    class TestController extends Controller {

    public function test()
    {

      $diamonds = diamonds::find(1);
      var_dump($diamonds);
    }

 }

Upvotes: 3

danbahrami
danbahrami

Reputation: 1012

Try adding the following lines above your class decleration in your controller file...

use App\Diamonds;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

(this assumes your model file is called Diamonds.php)

Upvotes: 2

Related Questions