How to create and use custom traits in Laravel 8/9

Chimeremze Prevail Ejimadu
3 min readDec 29, 2022

--

Photo by Ben Griffiths on Unsplash

Traits are simply inherited characteristics. In programming, traits are a mechanism for code reuse in single inheritance languages such as PHP.

A trait enables a developer to reuse sets of methods freely in several independent classes living in different class hierarchies thereby reducing some limitations of single inheritance languages.

Traits are created when we have functions to be shared among different methods, methods to be reused in different paths of the code.

How to create a trait

We can create a trait in Laravel using the trait keyword and can access it using the use keyword, we then call it via $this if it is not a static method otherwise use self::.

Note: Traits are not peculiar to Laravel or any framework, it can be used anyhow and anywhere in PHP.

What trait are we going to create? Let us create an Image Upload trait. Most applications require users to upload photos at different times, this might include during Profile Creation, making a post, creating a story, updating profile, uploading Proof of payment, completing KYC, etc. So we see that in each case, we should not repeat the logic and code of uploading the photo, we should have an ImageUpload trait to handle that.

Let’s create our Trait

Step 1: Create a Traits directory and file

Create a folder inside app directory named Traits and inside it create ImageUpload.php hand inside this, create a single method upload() function. Paste the code below:

app/Traits/ImageUpload.php

<?php
namespace App\Traits;

use Illuminate\Http\Request;

trait ImageUpload {

/**
* @param Request $request
* @return $this|false|string
*/
public function upload(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;
}
}

Step 2. Use the trait inside a controller

Let us say we have a PostController at

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

use App\Traits\ImageUpload;

class PostController extends Controller
{


use ImageUpload;
/**
* Persist a resource in database.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{

$image = $this->upload($request, 'image', 'posts');

Post::create([
'title' => $request->title,
'body' => $request->body,
'author_id' => $request->author,
'image' => $image
]);

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

}
}

Easy, right?

We added the trait to the controller by adding use ImageUpload inside the controller class. and called it with $this->functionName.

You have seen how to use traits to make codes reusable, and it makes our controllers to be readable too. We can use traits to register users or do many other things that can be reused in different parts of the app.

Now, we might have the question, when do we use traits instead of actions or services or jobs or even events and listeners. I will be writing an exhaustive article on how to use these wonderful Laravel features and nice ways to use them to make your Laravel code better and more maintainable.

Stay tuned!!! I will be back with some more cool Laravel tutorials in the next article. I hope you liked the article. Don’t forget to follow me 😇 and give some clap 👏. And if you have any questions feel free to comment.

Thank you 🙏

Thanks a lot for reading till end 🙏 You can contact me in case if you need any assistance:
Email: prevailexcellent@gmail.com
Github: https://github.com/PrevailExcel
LinkedIn: https://www.linkedin.com/in/chimeremeze-prevail-ejimadu-3a3535219
Twitter: https://twitter.com/EjimaduPrevail

--

--

Chimeremze Prevail Ejimadu

Laravel Developer + Writer + Entrepreneur + Open source contributor + Founder + Open for projects & collaborations. Hit FOLLOW ⤵