I am having an issue utilizing traits in a laravel enviroment.
I have attempting to access the trait from wtihin a model in laravel and am getting trait not found error. Below is my trait, this is stored in the app\Traits folder and is named testTrait.php
<?php
namespace App\Traits;
trait test{
public function printTest()
{
$test = 'test';
return $test;
}
}
This is the model I am using to try and access it, this is stored in the app\Models folder and otherwise works fine without attempting to use the trait
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Traits\testTrait;
class Home extends Model
{
use testTrait;
public function someMethod()
{
/*
something here
*/
}
}
I assume it might have something to do with namespacing and the fact that I have to assign the App\Models namespace but even if I change or remove this it doesn't work.
Your file may be named testTrait.php, but you've called the trait in that file plain old test.
trait test { ... }
Rename it to testTrait in the testTrait.php file.
trait testTrait { ... }
You have defined your trait as trait test{ but in your model you are using wrong trait name use testTrait;
change it to
use test;
Related
Normally I have a question about something not working, now I have a question about something that IS working, I am just confused as to why. This is the structure that I have in Laravel:
ExampleController
use App\Http\Traits\Trait1;
use App\Http\Traits\Trait2;
ExampleController extends Controller {
use Trait1, Trait2;
public function index()
{
// I can use methods from Trait1 and Trait2 here, works fine
}
}
Trait1
namespace App\Http\Traits;
trait Trait1 {
exampleMethodTrait1()
{
}
}
Trait2
namespace App\Http\Traits;
trait Trait2 {
$test = $this->exampleMethodTrait1();
}
Calling a method defined in Trait1 from Trait2 actually works, while I have not added use App\Http\Traits\Trait1; in Trait2. Is that because they are both loaded in the controller?
Okay, Let me put same code and explain you why it is working.
Trait1
<?php
namespace App\Http\Traits;
trait Trait1 {
public function exampleMethodTrait1()
{
echo 'okay';
}
}
?>
Trait 2
<?php
namespace App\Http\Traits;
trait Trait2 {
public function bar() {
var_dump(get_class($this));
$test = $this->exampleMethodTrait1();
}
}
?>
MyController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Traits\Trait1;
use App\Http\Traits\Trait2;
class MyController extends Controller
{
use Trait1, Trait2;
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$this->bar();
}
}
Now, if you will notice in Trait 2, var_dump(get_class($this)); $this is instance of MyController and not instance of trait 2, that is how it is working and it is expected behavior.
Now if you want to know if you can use one trait in side another
YES
You can do like
TaraitA
Trait A {
}
TraitB
Trait B {
use A;
}
And it will work fine.
Yes, they are both loaded in your controller as a part of it therefore they have access between them also controller methods
See the example 4
https://www.php.net/manual/en/language.oop5.traits.php
Regards
I think your confusion comes from believing that the $this inside a trait corresponds to the trait itself. But it is not.
Traits are nothing by themselves: they exists only in the context of a real class, as a helper to copy-paste methods around but not visually polluting your actual classes.
The $this you use to call exampleMethodTrait1 is not an instance of Trait2 (nor Trait1) but an instance of ExampleController, that has copied the methods over from the traits.
This doesn't happen only with traits, though, but also with parent classes in the hierarchy:
Example
abstract class Base {} // First level of inheritance
class Building extends Base {} // Second level of inheritance
class House extends Building {} // Last level of inheritance
$this (and static) always corresponds to an instance of the most concrete class of the hierarchy (the last level of inheritance).
self instead refers to the actual class instance (the same level of inheritance where the method is defined). Still never a trait, they cannot be instantiated by themselves.
the traits are not part of the hierarchy, but blindly pasted where you use them.
I'm currently working on a PHP trait thay will help me to reuse code in some class controllers that I have using Laravel framework.
I wanted to make the trait methods as dynamic as I could but when trying to access to a class that my parent class imported, I get a Class not found exception.
My class controller is as follows:
namespace App\Http\Controllers\Admin;
use App\Models\ {
Curso,
Leccion,
Diapositiva,
ImagenDiapositiva
};
use App\Traits\TestTrait;
class DiapositivasController extends Controller{
use TestTrait;
public function addRecord(Request $request){
$request->class_name = 'ImagenDiapositiva';
$this->addImage($request);
}
}
My Trait:
namespace App\Traits;
trait TestTrait{
public function addImage($request){
$class_name = $request->class_name;
$diapositiva = new $class_name;
//extra code
}
}
So my doubt is, do I have to include the model classes I want to use inside my Trait again or am I doing something else wrong?
if you use new with a variable class name, you have to use the fully qualified class name. I'm guessing new $class_name is the root cause of the issue here, since $class_name would have to be something like: 'App\Models\ImagenDiapositiva' or whatever the full namespace is. Just have to change the call $request->class_name = 'ImagenDiapositiva'; to reflect the full name of the class.
I'm trying to place a trait inside a class called Page. I also need to rename a trait function so that it doesn't clash with an existing class function. I thought I did all this successfully however I get an error that points to the wrong location?!
Call to undefined function App\Pages\Models\myTraitDefaultScope()
I've also tried: MyTrait\defaultScope($query) instead of trying to rename the conflicting function. But I then get the following error:
Call to undefined function App\MyTrait\defaultScope()
Below is the trait and class contained in separate files.
<?php
namespace App;
use Illuminate\Support\Facades\Auth;
trait MyTrait{
public function defaultScope($query){
return $query->where('active', '1')
}
}
.
<?php namespace Modules\Pages\Models;
use Illuminate\Database\Eloquent\Model;
use App\MyTrait;
class Page extends Model {
use MyTrait{
MyTrait::defaultScope as myTraitDefaultScope;
}
public function defaultScope($query){
return myTraitDefaultScope($query);
}
}
I'm not all that awesome at this so please don't shoot if I've got something badly wrong :)
When you 'use' a trait in your class, the class inherits all the methods and properties of the trait, like if it was extending an abstract class or an interface
So, this method of MyTrait:
public function defaultScope($query){
return $query->where('active', '1')
}
will be inherited by your Page class
As you have aliased this method as: myTraitDefaultScope, to call the method you should call it in the same way you would call every other method of the Page class:
public function defaultScope($query){
//call the method of the class
return $this->myTraitDefaultScope($query);
}
As you're using trait. So it points to the current or parent class. Thus, calling any method should be like $this->method($params); syntax.
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.
I have created a common class in app/Classes/Common.php
but whenever i try to access a model in a class function.
$new_booking_request = BookingRequest::where('host_id','=',Auth::id())
I am getting this error
Class 'App\Models\BookingRequest' not found
Even other classes like Auth, URL and Cookie are not working.
Is there a way to bring all classes in my Common class scope?
You get this issue when your namespace is wrong you or you forgot to namespace.
Since common.php is inside App/Classes, inside Common.php do somethng like this:
<?php namespace App\Classes;
use View, Auth, URL;
class Common {
//class methods
}
Also ensure your model class has the correct namespace, if BookingRequest.php is located inside App\Models then inside BookingRequest.php do this:
<?php namespace App\Models;
BookingRequest extends \Eloquent {
//other definitions
}
Then if you wish to use BookingRequest.php outside its namespace or in another namespace like so:
<?php namespace App\Classes;
use App\Models\BookingRequest;
use View, Auth, URL;
class Common {
//class methods
}
In Laravel 5 everything is namespaced, make sure your class has a proper namespace and that you are calling it using that same namespace you specified.
To include classes in another class make sure that you use the use keyword to import the necessary classes on top of your class definition. Also you can call the class globally with the \. Ex: \Auth, \URL and \Cookie
For the namespace in L5 here is a quick example:
<?php namespace App\Models;
class BookingRequest {
// class definition
}
then when trying to call that class, either call the full namespace path of the function, or include the function.
<?php
class HomeController extends Controller {
public function index()
{
$newBookingRequest = App\Models\BookingRequest::where('host_id','=',Auth::id());
}
}
OR
<?php namespace App\Controllers;
use App\Models\BookingRequest; // Include the class
class HomeController extends Controller {
public function index()
{
$newBookingRequest = BookingRequest::where('host_id','=',Auth::id());
}
}
PS:
Please use camelCase when defining class attributes and methods as this helps for a better code-styling and naming conventions when using the L5 framework.