Today, i will show you step by step how to make a trait in laravel application. you can easily create traits and use it in laravel controller and modal. i will give you simple example of creating traits in laravel example.
You can easily use php laravel traits in laravel 5 and laravel 6 application.
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.
Here, i will give you very simple example how to create trait and how to use trait in laravel project. we will create one trait “ImageTrait”. in that trait we will write code for image upload. So where ever we need upload image then we can use this ImageTrait trait. For example we have use profile, product picture etc, so we can use same trait method we don’t require to write again and again same code.
I written few days ago image uploading with laravel 6. you can see that tutorial from here: Image Upload in Laravel 6. You can see on that post i written code for image upload. we can use trait for image upload on that example like as bellow example:
We need to create our custom trait as ImageTrait on new folder “Traits”. 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;
}
}
Now let’s see bellow controller code, you can see how we can use this trait in our controller method. you can same use it again and again when you require to upload image.
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 it in your other controller same trait.
I hope it can help you…