Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a model in Laravel 5?

Tags:

php

laravel

model

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...

like image 670
Avi Avatar asked Mar 09 '15 08:03

Avi


People also ask

How do you call a model function in a model in Laravel?

In Model: namespace App; use Illuminate\Database\Eloquent\Model; class Authentication extends Model { protected $table="canteens"; public function test(){ return "This is a test function"; // you should return response of model function not echo on function calling. } }

What does get () do in Laravel?

This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.

Where can I find model in Laravel?

Models in Laravel 5.5 are created inside the app folder. Models are mostly used to interact with the database using Eloquent ORM.


2 Answers

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.

like image 75
wiesson Avatar answered Sep 20 '22 23:09

wiesson


  //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);
    }

 }
like image 45
Raheel Avatar answered Sep 21 '22 23:09

Raheel