DEV Community

Cover image for Laravel 8 - Traits (3 Easy Steps)
DaleLanto
DaleLanto

Posted on

Laravel 8 - Traits (3 Easy Steps)

Using traits is one of the best practices alongside OOP(Object-Oriented Programming) and [SOLID Principles] in PHP.(https://dev.to/dalelantowork/solid-principles-object-oriented-programming-in-php-3p3e)

What is a Trait?
Traits are a mechanism for code reuse in single inheritance languages such as PHP.

A trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

In simple terms Traits is a group of methods that you want to include within another class. You can easily reuse that methods to another class. Trait is save to write same code again and again.

Let's Start Creating Our Own Custom Trait!

We will create one trait ImageTrait and in that trait we will write code for image upload.

Whenever we need to upload image then we can use this ImageTrait trait.

Step 1: Create Traits file and ImageTrait

Create a folder inside app directory named Traits and inside it create ImageTrait

Let's create a new trait with verifyAndUpload() function. Paste the code below:

app/Traits/ImageTrait.php

<?php

namespace App\Traits;

use Illuminate\Http\Request;

trait ImageTrait {

    /**
     * @param Request $request
     * @return $this|false|string
     */
    public function verifyAndUpload(Request $request, $fieldname = 'image', $directory = 'images' ) {

        if( $request->hasFile( $fieldname ) ) {

            if (!$request->file($fieldname)->isValid()) {

                flash('Invalid Image!')->error()->important();

                return redirect()->back()->withInput();

            }

            return $request->file($fieldname)->store($directory, 'public');

        }

        return null;

    }

}
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the controller that will use ImageTrait

Paste the code below.

app/Http/Controllers/ItemController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item;

class ItemController extends Controller
{
     /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('imageUpload');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->all();

        $input['image'] = '';

        Item::create($input);

        return back()
            ->with('success','record created successfully.');

    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Insert and use ImageTrait on your Controller

Paste the uses of ImageTrait.
app/Http/Controllers/ItemController.php

use App\Traits\ImageTrait;
Enter fullscreen mode Exit fullscreen mode
  • at the top part
use ImageTrait;
Enter fullscreen mode Exit fullscreen mode
  • inside the controller class
$input['image'] = $this->verifyAndUpload($request, 'image', 'images');
Enter fullscreen mode Exit fullscreen mode
  • using the function inside the trait

Now it should like this!

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item;
use App\Traits\ImageTrait;

class ItemController extends Controller
{
    use ImageTrait;
     /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('imageUpload');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->all();

        $input['image'] = $this->verifyAndUpload($request, 'image', 'images');

        Item::create($input);

        return back()
            ->with('success','record created successfully.');

    }
}

Enter fullscreen mode Exit fullscreen mode

Hurray we have successfully created and applied Traits! You can now use this in your projects and improve the readability and stability of your code!

Image description

Top comments (5)

Collapse
 
elgallotito profile image
Eduardo Tapia

Hello, I do what you say but I get an error: Trait "App\Traits\MessageTrait" not found.
Do I need to register the file in composer.json?
If so, in what section of composer.json?

Thank you

Collapse
 
mohfa24 profile image
mohfa24

hello.
maybe you forgot to add
namespace App\Traits;
at top of your trait file "MessageTrait.php"

Collapse
 
elgallotito profile image
Eduardo Tapia

No. I have it added just like you say.

Do I need to register the file in composer.json?
If so, in what section of composer.json?

Thread Thread
 
msnmongare profile image
Sospeter Mongare

Nope, You don't have too.

Collapse
 
wteja profile image
Weerayut Teja

Thank you, this really helpful ❤️🙏