Laravel namespace in relations confused me - php

In my app I have Event and User models.Because of Event model I have to put it into namespace .so I created namespace as of following.
Event
<?php namespace App\Models;
class Event extends \Eloquent {
public function user()
{
return $this->belongsTo('User');
}
User
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
use App\Models\Event;
class User extends Eloquent implements UserInterface, RemindableInterface {
public function events()
{
return $this->hasMany('Event');
}
The relations between User and Event are simple OneToMany. So in my EventController I use POST method to create new event resource .
$e = new Event(array('keys'=>'values')); //without user_id filled
$user->events()->save($e);
At the same time i got an error .
Call to undefined method Illuminate\Support\Facades\Event::newQuery()
If I am not wrong i guess it is namespace error.But namespaces are already declared correctly I guess.
But I try visiting similar questions and used alternative way in relationship and then it worked fine.Personally I don't find it satisfied.Any idea why this is occurred ?
Change the above relation to
public function events()
{
return $this->hasMany('\App\Models\Event');
}

If you put Event inside a namespace you need to use it with it's fully qualified classname.
You can either import it into your controller:
use App\Models\Event;
Or specify the namespace inline:
new App\Models\Event();
Also, I would recommend that if you create a namespace for models that you put all of them in there. (User is missing a namespace in your code)

Related

Laravel mutual methods for many models

I added a method to one of my models:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Test extends Model
{
public static function boot()
{
parent::boot();
static::created(function ($model) {
//log $model or maybe do something more complex here
});
}
}
And i wish to extend the same behaviour to many other models. Copy pasting this doesent seem like a good idea because if something changes i dont want to change it in different places. What is the best solution to write this only once and get the same behaviour to multiple models?
Traits are built for that. Write once and use on all classes.
Create a trait in app/Traits/MyTraitName.php
<?php
namespace App\Traits;
use Carbon\Carbon;
trait MyTraitName
{
public function someName() {
// TO DO;
}
}
and then just import it on top of any model class for example User:
<?php
namespace App;
use App\Traits\MyTraitName;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable, MyTraitName;
..............
The difference between extending a class and making a trait is that when you make a trait that function is already written and it's automatically used the same way on every model, and extending from some base class is better if that function is not going to be the same for every Model.

Laravel 5.4 class User not found

I am using laravel 5.4 i got and error that
FatalThrowableError in HasRelationships.php line 487: Class 'User' not
found
In my model i am using the following code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Auth;
use App\User;
class Review extends Model
{
public function user()
{
return $this->belongsTo('User');
}
}
Could any one help me fix this error
You should use App\User in belongsTo. If you provide only User it will look for User in the base directory. But User is in the App namespace. :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Auth;
use App\User;
class Review extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
Edit :
belongsTo require a namespace of a model you can achieve it either with above mentioned method or with User::class. As it will also return the namespace of User class.
return $this->belongsTo(User::class);

Laravel: Model Class not found in relationships

Using Relationships first time and having issue to understand it.
I have a Student Class and a Course Model Class. A student can take many courses. In Student Model I do this:
public function course()
{
return $this->belongsTo('Course');
}
and in controller when I do this: .$student->course()->course_title it gives an error:
FatalThrowableError in Model.php line 779:
Class 'Course' not found
What am I doing wrong?
replace your code with it
public function course()
{
return $this->belongsTo(Course::class);
}
Make sure your namespace in your Course class matches 'App\Models'. You might be trying to access an "empty" namespace.
Namespaces are declared at the top of your class file. So for example:
Course.php:
namespace App\Models;
use Illuminate\Http\Request;
...
class Course extends Model { ... }
OtherClass.php
namespace App\Models;
use Illuminate\Http\Request;
...
class OtherClass extends Model {
...
public function course()
{
return $this->belongsTo('App\Models\Course')
}
}
Please note that the namespace declared at the top of Course.php matches the path provided to the relationship method (return) belongsTo(). You can also provide Course::class to the belongsTo method, but you need to import aka use the class in your php class.
I hope this helps!
I had the same problem and i solved it by adding a name space in the top of my model
for your case,
use \App\Course ; // Your name space of your class in relation
Hope this help others
NB : I used Laravel 5.0

Laravel 5 global model methods?

I have a number of tables / models setup that have 'locked_at' and 'locked_by' columns, in essence what I would like to do is call something like:
$model->lock();
This method would check that row is not already locked, set the both cells and then save the model.
I can create the lock method inside each of my models, but that doesn't seem like the best idea. I would prefer to create the method once and have it accessible to all models.
Is there a way of doing this in laravel?
Just like ceejayoz suggested, you could achieve it by using a Trait.
Step 1
Create a folder called Traits and inside that create trait class like the following
<?php
namespace App\Traits;
trait Lockable {
public function lock() {
$this->lock = 1;
$this->save();
}
}
Step 2:
Now import the trait on your model class like the following
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Traits\Lockable;
class User extends Authenticatable
{
use Lockable;
}
Thats it! Now you could call the function like
$user = \App\User::find(1);
$user->lock();
You can create BaseModel class that extends Model and make all your models that using lock() method extend BaseModel class instead of theModel. Then just define lock() method in the BaseModel class.

Laravel can't find class in namespace

I using Laravel, I have a Model class under App/Models
<?php
namespace App\Models;
class TodoList extends \Eloquent{
public function listItems(){
return $this->hasMany('TodoItem');
}
}
In my Controller I have included the namespace as follows:
namespace App\Http\Controllers;
...
use App\Models\TodoItem;
use App\Models\TodoList;
class TodoListController extends Controller
My method looks like this:
public function show($id)
{
$list=TodoList::findOrFail($id);
return \View::make('todos.show')->with('list', $todo_list);
}
but when I call to a request i get the error:
FatalErrorException in TodoListController.php line 75: Class
'App\Models\TodoList' not found
Trying running composer dump-autoload. Basically your classes become cached so you need to tell Laravel to look for newly added classes.
I'm not sure, just try this :
namespace App\Models;
use Illuminate\Database\Eloquent\Model as Eloquent;
class TodoList extends Eloquent{
public function listItems(){
return $this->hasMany('TodoItem');
}
}
Here is the code from the docs, but for your example. Note the use Model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class TodoList extends Model {
//insert public function listItems() here
}
Hope this is helpful!
Make sure the file is in the correct folder and has the same name caption as the Class you want to import.
If the caption of the file "TodoList" is not TodoList.php but Todolist.php for example, Laravel wont find it.
Depending on your setup running "composer dump" might help to refresh autoload files.

Categories