How to call a tag method with an alias

I am trying to put a dash inside a class called "Page". I also need to rename the feature function so that it does not interfere with an existing class function. I thought I did all this successfully, however I have an error indicating the wrong location ?!

Call to undefined function App\Pages\Models\myTraitDefaultScope()

I also tried: MyTrait\defaultScope($query) instead of renaming the conflicting function. But I get the following error:

Call to undefined function App\MyTrait\defaultScope()

Below is the attribute 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 so keen on this, so please donโ€™t shoot if I have something bad.

+7
php namespaces class traits laravel
source share
2 answers

When you use an attribute in your class, the class inherits all the methods and properties of this attribute, for example, if it extends an abstract class or interface

So this method is MyTrait :

 public function defaultScope($query){ return $query->where('active', '1') } 

will be inherited by your Page class

As you wrote this method as: myTraitDefaultScope , to call a method, you must call it 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); } 
+4
source share

How do you use the trait. Thus, it points to the current or parent class. Thus, a call to any method should look like the syntax $ this-> ($ params); .

+1
source share

All Articles