Definition of Traits in Laravel with Example ?

What is Traits in Laravel ?

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

In this tutorial we ‘have to create a trait for image upload functionality is a great way to ensure code reusability. You can use the same trait in multiple models or controllers where image uploads are required, like for profiles, product pictures, or any other entities requiring image handling.

Here is the introduction to Laravel Traits in simple words:

  • Traits are a way to reuse code in Laravel.
  • They are similar to classes, but they cannot be instantiated on their own.
  • Traits can be included in classes to give them additional methods and functionality.
  • Traits offer several advantages, including code reusability, flexibility in composition, and adherence to the Single Responsibility Principle.
  • Using traits can help you to organize your code, promote code reuse, simplify code maintenance, and facilitate code sharing within a team.

We will create new trait with verifyAndUpload(). verifyAndUpload() helps to upload image from controller. So let’s create bellow file and write code as like bellow code:

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;

    }
  
}

So, let’s write code as bellow for controller.

app/Http/Controllers/ItemController.php
<?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.');
   
    }
}

Now you can use traits …………..

Hi I am Amit Kumar Thakur Experienced as s Software Developer with a demonstrated history of working in the information technology and services industry. Skilled in HTML, CSS, Bootstrap4, PHP, Laravel-9 , REST API,FB API,Google API, Youtube Api, Bitbucket,Github,Linux and jQuery. Strong engineering professional focused in Computer/Information Technology Administration and Management. Currently my profile is to Software Developer, analyze the requirement, creating frame for web application, coding and maintenance.

Related Posts

How to Crawl any website Meta Title and Meta Description in Laravel ?

1st step install below package. Next to create Controller First go to route and put below code Next go to controller and put below code Next go…

SQLSTATE[HY000] [2002] No such file or directory (Connection: mysql, SQL: insert into `oauth_clients` (`user_id`, `name`, `secret`

In this tutorial i’m going to solve the error SQLSTATE[HY000] [2002] No such file or directory (Connection: mysql, SQL: insert into oauth_clients (user_id, name, secret Error :-…

Top 20 Laravel Interview Question in 2024

In this tutorial im going share interview experience For laravel developer. A list of top frequently asked Laravel Interview Questions and answers are given below. Q #1) What is…

How to Get Google Analytics API key ?

In this tutorial we’re going to share how to get the google Analytics API key. I have shared in very easy way. First go enable Google analytics…

Youtube Subscriber Count in ReactJs

In this tutorial i’m going to learn how to count YouTube Subsribers count, views count as well, as define below. In order to install your app, first…

How to Disable Laravel’s Eloquent timestamps in laravel ?

In this tutorial we’re going to share how to disable the automatic created_at and updated_at timestamps in Laravel’s Eloquent models, along with explanations of different scenarios: 1st…

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x