Gammer
Gammer

Reputation: 5608

Laravel 5 Model class

I created model class in app root directory. Since laravel 5 use app root directory for models. I didn't created another folder for Models.

class Posts extends Eloquent{}

And in routes.php :

Route::get('/', function () {

  $painting = Posts;
  $painting->title = 'Do no Wrong';
  $painting->artist = 'D. Do right';
  $painting->year = 2014;
  $painting->save();

  return view('welcome');
});

It throws the following error :

Class 'Painting' not found

Upvotes: 2

Views: 3734

Answers (4)

Jeemusu
Jeemusu

Reputation: 10533

The filename of your Model must reflect the class name. So for a Posts model, the file should be named Posts.php. Assuming the model has been placed in the App/ directory of your Laravel installation, the Model should look something like this:

<?php 

namespace App;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model 
{

}

You can then access the Posts model in your route under the App namespace as App\Posts:

Route::get('/', function () {

  $painting = new App\Posts;
  $painting->title = 'Do no Wrong';
  $painting->artist = 'D. Do right';
  $painting->year = 2014;
  $painting->save();

  return view('welcome');
});

The above should work, but I would recommend using non-plural names for your Models. So ideally your Posts Model should be called Post, while the table in the database will be called posts. This is the convention Laravel expects you to follow when naming your classes and database tables.

Upvotes: 3

Emeka Mbah
Emeka Mbah

Reputation: 17545

You are missing the namespace and new statement;

Try:

Route::get('/', function () {

  $painting = new App\Posts;
  $painting->title = 'Do no Wrong';
  $painting->artist = 'D. Do right';
  $painting->year = 2014;
  $painting->save();

  return view('welcome');
});

Your model should look like this:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model{

}

Upvotes: 0

Ben Chamberlin
Ben Chamberlin

Reputation: 731

Change $painting = Posts; to $painting = new Posts;

Additionally, I think you're supposed to create Eloquent models like so:

namespace App;
use Illuminate\Database\Eloquent\Model;

class Posts extends Model

Instead of trying to extend 'Eloquent'.

Upvotes: 0

Md Adil
Md Adil

Reputation: 307

you can save records use create method

Posts::create([ 'title' => 'Do no Wrong', 'artist' = 'D. Do right']);

or simply you can instance Posts class and use your code.

Route::get('/', function () {
  $painting = new Posts;
  $painting->title = 'Do no Wrong';
  $painting->artist = 'D. Do right';
  $painting->year = 2014;
  $painting->save();
  return view('welcome');
});

Upvotes: 0

Related Questions