Models like "MyModel" (2 words) does not load - php

I have created an example model:
class ExampleModel extends Eloquent {
protected $table = 'example_model';
}
Then I tried to call ExampleModel::all() which returned an error function all() does not exist (seems like the class is created but without Eloquent functions). After changing model name (and file name) to Examplemodel (now the model name is one word) it works. The problem is not that I misspelled something as I have checked that like a hundred of times and my file+class names are matching.
Am I missing something about auto loading?
I am on windows so I also tried changing file's name to Examplemodel without changing the class name but it still seems to load the class without Eloquent methods.

Did you do Autoload (dumpautoload)?
Because of this case works for me.

Do composer dump-autoload
As the following works for me:
class ExampleTest extends \Eloquent {
protected $table = 'users';
}
Then on the routes file I have:
Route::get('/', function()
{
$data = ExampleTest::all();
return $data;
});
This gives me the data from my users table.

create a file example.php in models folder and then write this:
class Example extends Eloquent {
protected $table = 'example_model';
}
and then try:
Example::all();
taken from here

I have found a problem. I had a migration with class same as my model. Laravel is auto loading models with migrations and it thought I was referring to migration instead of a model.
After fixing that of course I had to run dumpautoload composer command.

Related

Can't eager-load a One-to-One relation in Laravel

In Laravel 5.2 I'm trying to eager load a User along with its Usersettings with this piece of code: App\User::with('usersettings')->get(), but it fails, and I can't seem to figure out why. This is the given error.
BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::usersettings()'
I've read the laravel docs and I've watched a lot of Laracasts, and this worked before, so I get the idea I'm missing something really small and probably obvious.
User.php
<?php
namespace App;
/* User with fields: id, email */
class User extends Illuminate\Database\Eloquent\Model {
protected $table = 'users';
public function usersettings() {
return $this->hasOne("App\Usersettings", "userid");
}
}
Usersettings.php
<?php
namespace App;
/* Settings with fields: id, userid, textcolor */
class Usersettings extends Illuminate\Database\Eloquent\Model {
protected $table = 'usersettings';
public function user() {
return $this->belongsTo('App\User', 'userid');
}
}
//Edit: I already tried lowercasing the s. This typo might have snuck in copying it to SO, but the error was there, and still is there, even after fixing it.
//Edit:
<?php
namespace App;
use App\UserSettings;
class User extends Illuminate\Database\Eloquent\Model {
protected $table = 'users';
public function settings() {
return $this->hasOne(UserSettings::class, "userid");
}
}
If I run php artisan tinker>>> App\User::with('settings')->get(), it works as expected, but below
<?php
namespace App;
use App\UserSettings;
class User extends Illuminate\Database\Eloquent\Model {
protected $table = 'users';
public function usersettings() {
return $this->hasOne(UserSettings::class, "userid");
}
}
gives BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::usersettings()' when I run php artisan tinker >>> App\User::with('usersettings')->get(). Likewise when I rename the method to abc and run php artisan tinker >>> App\User::with('abc')->get() (that fails as well)
You mistyped when defining the relation on the User model:
public function usersettings() {
return $this->hasOne("App\Usersettings", "userid");
}
I would suggest some cleanup:
name the tables 'users' and 'user_settings',
rename the field 'userid' to 'user_id',
rename the 'Usersettings' model to 'UserSettings'.
That way you dont need to explicitly define table names and foreign keys, because you follow the conventions and Laravel can "guess" those.
You can also rename the the relation 'usersettings()' to 'settings()', since its obvious that they're the users' settings. Then you can fetch it like: 'User::with('settings')->get()'.
Did you try running composer dump-autoload after you changed your model relationships?
Just to make sure you're aware of this: you don't actually need to define the relationship in your UserSettings model to achieve what you want, only define the relationship in the User model. This is because you'd only need to get the settings in the context of the User, not the other way around.
Code for the User model:
<?php
namespace App;
use App\UserSettings;
class User extends Illuminate\Database\Eloquent\Model {
public function userSettings() {
return $this->hasOne(UserSettings::class);
}
}
UserSettings model: make sure it's camel case and that userid is present in your migration (the convention in your case would be to have user_id, so I would rename that column in your migration because then Eloquent will pick it up automatically and you don't need the second parameter in your User model's hasOne() definition).
Also, rename your table to user_settings if you can. That's another Eloquent convention, this one being that the model name UserSettings translates the camel case S letter in the middle of the classname to _ (and as a matter of fact, you shouldn't even need to explicitly state the table name if you've used the name user_settings).
Code for the UserSettings model:
<?php
namespace App;
/* Settings with fields: id, userid, textcolor */
class UserSettings extends Illuminate\Database\Eloquent\Model {
protected $table = 'user_settings';
}
Now, you should be able to do the below action. Note that the with parameter needs to be the relation function name from the User model.
$usersThatHaveSettingsIncludedInTheResults = User::with('userSettings')->get();

Troubleshooting referencing a model in a laravel controller

I've been trying unsuccessfully to resolve an error in a laravel 5.2 app (carfreak).
FatalErrorException in PropertyController.php line 85:
Class 'App\Models\CarModel' not found
I have moved the default user model to a folder app/models and made the necessary changes so that it's all working fine.
Now I have a new controller CarController, and a new model, CarModel that are just not working. It seems to be such a simple problem with namespaces, but I am unable to resolve it.
is the model in the models folder? Yes. carfreak\app\Models\CarModel.php
is the controller namespace correct? Yes... namespace carfreak\Http\Controllers;
does the controller reference the model? Yes...use App\Models\CarModel;
is the model namespace correct? Yes... namespace carfreak\Models;
I am able to create different versions of the error by playing with the CarController but no permutation I can think of has worked.
EDIT: Controller and Model added...
EDIT: More details added:
The irony of this is that I can php artisan make:model sanityCheck and it will create a model in the \app root (i.e. not in app\models)... and that model can be called just fine. If I put my CarController back in the root, and change it's namespace appropriately, it still doesn't work. It's almost like I have some stupid spelling error in the class name or something, but I've copied and pasted class names into my filename, class declaration, "use" declarations, etc. and it. still. doesnt. work. Aargh!
//this is carModel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CarModel extends Model
{
//
/**
* The attributes that are mass assignable.
* #var array
*/
protected $fillable = [
'colourOfCar',
];
}
//this is carController
<?php
namespace carfreak\Http\Controllers;
use Illuminate\Http\Request;
//use \carfreak\app\Models\CarModel;
use App\Models\CarModel;
class CarController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request)
{
// validate the data
$this->validate($request, array(
'CarColour' => 'required|max:50'
));
// store in the database
$newCar = new CarModel;
dd($request);
}
}
This looks wrong use \carfreak\app\Models\CarModel; should be use App\Models\CarModel in this is carController
Casing is important on linux. The namespace generally is used in a PSR Aloader to find the file. And Linux filesystem is case sensitive. So the CareModel.php file should be located in App/Models/CarModel.php
But I never used Laravel...
Well, here it is. I solved it by asking myself this question: If I'm having so much trouble namespacing, referencing and organising my models, then maybe I can get artisan to do it for me.
The post that got me thinking differently was Mansoor Akhtar's advice here: How do I instruct artisan to save model to specific directory?
Get artisan to make the model in the right place first time.
php artisan make:model Models/CarModel
In the Controller, reference the model correctly
use name-of-app\Models\CarModel;
There may or may not be cache flushing involved in my problem. I was eventially restarting my XAMPP after every change to ensure no caching was involved. I also tried
php artisan cache:clear

Using Laravel 5 Model

I have created a model using
php artisan make:model Sessions
which creates a model named Sessions in the App\ folder. My Model (Sessions) and the controller(School) calling the model are below
Model (Sessions):
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Sessions extends Model {
//
protected $table = "sch_sessions";
protected $primaryKey = "session_id";
}
Controller (School)
<?php
namespace App\Http\Controllers;
use App;
class SchoolController extends Controller {
public function sessionManagement(){
$Sessions = Sessions::all();
}
}
I get the following error
FatalErrorException in SchoolController.php line 7: Class
'App\Http\Controllers\Session' not found
I've tried putting the model in a folder and "use"ing it but nada. I'm stumped as to why the error is referring to a controller in the first place. Can anyone see something I don't (can't) please?
add on the top
use App\Sessions;
or use it with prefix
\App\Sessions::all();
If user Ali Mohammed's answer doesn't clear it up for you, it looks to me like your error is happening elsewhere. App\Http\Controllers\Session note Session is not plural.
Are you attempting to use the Session class elsewhere in your controller? If so, make sure to prefix it so it's using the Session declared in the global namespace. You can do this with \Session.

Database Table custom naming convention Laravel Eloquent

I'm trying to retrieve data from a table called completion_date using Eloquent. My Model name is Completion and as per laravel documentation, i should declare a (protected) table name or else Eloquent will use 'completions' as the default table name. So i did this declaration.
I'm getting problems with my Controller since i dont know which name to use to refer to my Model when i'm making the View. I'm getting an InvalidArgumentException that View [completion.lsz] not found. if i just use my model name to make the View.
Error:
InvalidArgumentException thrown with message "View [completion.lsz] not found."
Can someone pls help out?
Model
<?php
//Model (file name: Completion)
class Completion extends Eloquent{
protected $table = 'completion_date';
public $timestamps = false;
}
Controller
class CompletionController extends BaseController {
public function index() {
$lsz = Completion::all();
return View::make('completion.lsz', ['completion' => $lsz]);
}
}
Route
Route::get('/Completion', 'CompletionController#index');
View names in Laravel work like a path. The . gets converted to a /
That means, your view resolves to the file app/views/completion/lsz.blade.php (or app/views/completion/lsz.php without Blade)
So you either have to change the name of your directory in the views folder to "completion" or change the view make command to:
View::make('lsz.lsz', ['completion' => $lsz]);
The error message says that the view file completion/lsz.blade.php was not found.
It's not related to the model or database.

Laravel 4 Model only works if i take another name for the class and file

Hello i have a Controller:
class AddressController extends BaseController {
public function showIndex()
{
$address = Postcode::all();
return 'hello';
}
And a Model (which doesn't work):
class Postcode extends Eloquent {
protected $table = 'postcode';
}
But it only works with another name like:
class Kla extends Eloquent {
protected $table = 'postcode';
}
Anybody knows why?
You have named something else in the root namespace as Postcode. Most common this is the database migration. This is why database migrations generally should be a class name describing what it is doing, so in your case CreatePostcodeTable.
This is also why you should be using namespaces.
Just to be clear in-case you don't understand namespaces. You have 2 classes with the same name. The composer autoloader has grabbed the first one it finds (the one that isn't your model) and tried to use it. There is no static method all on the other class so you get an error (which you should have pasted in your question).

Categories