How to Create Traits in Laravel6?

  1455 views   4 months ago Laravel

In this article, I will share with you what is trais in laravel and how it used in our laravel application? Here in this article, i will give you one simple example of creating your own traits in your laravel application and how it will be used in your laravel application. but the first thing we will know why traits are defined in laravel?

What is Traits?

One of the major problems in PHP you can inherit only a single class with any other class. This means a class can only inherit from one other class. For example, it might be desirable to inherit methods from a couple of different classes in order to prevent code duplication. In PHP 5.4 a new feature of the language was added known as Traits and is used extensively in the Laravel Framework.

Step - 1 : Create Traits

In our first step, we need to create app\Traits\StoreImageTrait.php a file as a traits in laravel. and just put the following code into it.

namespace App\Traits;

use Illuminate\Http\Request;

trait StoreImageTrait {
    public function verifyAndStoreImage( Request $request, $fieldname = 'image', $directory = 'unknown' ) {
        if( $request->hasFile( $fieldname ) ) {
            if (!$request->file($fieldname)->isValid()) {
                flash('Invalid Image!')->error()->important();
                return redirect()->back()->withInput();
            }
            return $request->file($fieldname)->store('image/' . $directory, 'public');
        }
        return null;
    }
}

Step - 2 : How to use Traits in Controller

After, creating our traits then now we will see how to use our created traits in our laravel application controller.

namespace App\Http\Controllers\Admin;

use App\Models\Admin\Post;
use Illuminate\Http\Request;
use App\Traits\StoreImageTrait;

class PostController extends Controller
{
    use StoreImageTrait;

    public function store(CreatePostRequest $request)
    {
        $formInput = $request->all();
        $formInput['image'] = $this->verifyAndStoreImage($request, 'image', 'post');
        $post = Post::create($formInput);
        flash('Post saved successfully.')->success();
        return redirect()->back();
    }
}
	

i hope this article will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com

Related Articles