Import library to Laravel 5

Asked

Viewed 1,208 times

0

What I need

I need to import the modified FPDF library to the project.

What I did

Code is below, but I created a folder "Libraries" inside "App" and put the library there (with the name FPDF.php), put in Aliasses the name of the class and its path, and include in composer.json the path of the folder there in the classmap. I also added namespace App\Libraries\FPDF; in the FPDF.php file inside Libraries.

My folder and file structure

inserir a descrição da imagem aqui

What happened

Well, it doesn’t take a genius to figure it out: he’s not finding class. inserir a descrição da imagem aqui

config app.php

'aliases' => [
 ...
 ...

'FPDF' => 'App\Libraries\FPDF',

Composer.json

"autoload": {
        "classmap": [
            "database",
            "app/Libraries"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },

Homecontroller.php

public function gerarPdf() {
        if (Input::has('numeroDocumento') && Input::has('mesReferencia') && Input::has('anoReferencia')) {
            $fpdf = new FPDF();
            $fpdf->AddPage();
            $fpdf->SetFont('Arial','B',16);
            $fpdf->Cell(40,10,'Hello World!');
            $fpdf->Output();
            exit;

        }
        else {
            return redirect()->back()->with('message', 'Por favor, digite todos os campos !');
        }
    }
  • Added to your controller the use App\Libraries\FPDF\FPDF ? In Laravel 5 the app folder is already autoload, no need to use the classmap

  • @gmsantos If I do so it gives Namespace declaration statement has to be the very first statement in the script. Need to remove something ?

  • The namespace has to be the first thing in your file (right after the <php tag?)

  • <?php namespace App Http Controllers; use View, Input, App Models Barcode, App Libraries FPDF; class Homecontroller extends Controller {

2 answers

1

The aliases you are instantiating are a class FPDF inside the namespace App\Libraries

in your config.php is like this

'aliases' => [
'FPDF' => 'App\Libraries\FPDF',

But what we want is to instantiate a class FPDF inside the namespace App\Libraries\FPDF

Should stay like this

'aliases' => [
'FPDF' => 'App\Libraries\FPDF\FPDF',

This way in your Homecontroller just give a use FPDF that should work

1


I believe that the FPDF class does not belong to any namespace, so to use it you would have to map in Composer.json:

"autoload": {
    "classmap": [
        "database",
        "app/Libraries/FPDF"
    ]
},

and in the controllers you would only need to do:

use FPDF;

and use:

$pdf = new FPDF();

documentation FPDF Library.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.