How to use traits in Laravel 5.4.18?

前端 未结 3 1594
清酒与你
清酒与你 2021-01-12 09:06

I need an example of where to exactly create the file, to write to it, and how to use the functions declared in the trait. I use Laravel Framework 5.4.18

3条回答
  •  借酒劲吻你
    2021-01-12 09:31

    I have Create a Traits directory in my Http directory with a Trait called BrandsTrait.php

    and use it like:

    use App\Http\Traits\BrandsTrait;
    
    class YourController extends Controller {
    
        use BrandsTrait;
    
        public function addProduct() {
    
            //$brands = Brand::all();
    
            // $brands = $this->BrandsTrait();  // this is wrong
            $brands = $this->brandsAll();
        }
    }
    

    Here is my BrandsTrait.php

    Note: Just like a normal function written in a certain namespace, you can use traits as well

提交回复
热议问题