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…


This content originally appeared on DEV Community and was authored by DEV Community

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;

    }

}

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.');

    }
}

Step 3: Insert and use ImageTrait on your Controller

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

use App\Traits\ImageTrait;
  • at the top part
use ImageTrait;
  • inside the controller class
$input['image'] = $this->verifyAndUpload($request, 'image', 'images');
  • 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.');

    }
}

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


This content originally appeared on DEV Community and was authored by DEV Community


Print Share Comment Cite Upload Translate Updates
APA

DEV Community | Sciencx (2022-03-04T03:57:27+00:00) Laravel 8 – Traits (3 Easy Steps). Retrieved from https://www.scien.cx/2022/03/04/laravel-8-traits-3-easy-steps/

MLA
" » Laravel 8 – Traits (3 Easy Steps)." DEV Community | Sciencx - Friday March 4, 2022, https://www.scien.cx/2022/03/04/laravel-8-traits-3-easy-steps/
HARVARD
DEV Community | Sciencx Friday March 4, 2022 » Laravel 8 – Traits (3 Easy Steps)., viewed ,<https://www.scien.cx/2022/03/04/laravel-8-traits-3-easy-steps/>
VANCOUVER
DEV Community | Sciencx - » Laravel 8 – Traits (3 Easy Steps). [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/03/04/laravel-8-traits-3-easy-steps/
CHICAGO
" » Laravel 8 – Traits (3 Easy Steps)." DEV Community | Sciencx - Accessed . https://www.scien.cx/2022/03/04/laravel-8-traits-3-easy-steps/
IEEE
" » Laravel 8 – Traits (3 Easy Steps)." DEV Community | Sciencx [Online]. Available: https://www.scien.cx/2022/03/04/laravel-8-traits-3-easy-steps/. [Accessed: ]
rf:citation
» Laravel 8 – Traits (3 Easy Steps) | DEV Community | Sciencx | https://www.scien.cx/2022/03/04/laravel-8-traits-3-easy-steps/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.