Create your own library on Laravel

Laravel, 2015-06-16 23:29:45 UTC

Repeatedly writing code is a bad habit. Sometimes we also need a specific code to be used on another project. To organize the code, we can do an approach that is widely known as library.

Here's how to create your own library on Laravel;

1. Open up /app/start/global.php file and add 'library folder' like code below;

app_path().'/commands',
app_path().'/controllers',
app_path().'/models',
app_path().'/database/seeds',
app_path().'/libraries',



2. Now you can create a PHP file in libraries.

Example; MyLibrary.php

<?php

class MyLibrary {

    public static function write( $message ) {
        return $message;
    }
}



3. And finally, you can call it via controller like this;

<?php
class MyController extends BaseController {
    
    public function testLibrary() {
        echo MyLibrary::write("testing");
    }
}



Share: