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 …………..