Create a PDF and send it by email

4

You see, I have created a view which has to create a PDF with a list of several users and send an e-mail attached to an email address. This is the form:

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Enviando el formulario a la empresa</div>

                <div class="card-body">
                    <form method="POST" action="pdf_empresa" novalidate>
                        @csrf

                        <div class="form-group row">
                            <label for="email" class="col-md-4 col-form-label text-md-right">Correo Electronico de la empresa</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required>

                                @if ($errors->has('email'))
                                    <span class="invalid-feedback">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="sector" class="col-md-4 col-form-label text-md-right">Sector</label>

                            <div class="col-md-6">
                                <select id="sector" class="form-control{{ $errors->has('sector') ? ' is-invalid' : '' }}" name="sector" value="{{ old('sector') }}" required autofocus>
                                    @foreach($sectores as $sector)
                                        <option value="{{$sector->nombre}}">{{$sector->nombre}}</option>
                                    @endforeach
                                </select>

                                @if ($errors->has('sector'))
                                    <span class="invalid-feedback">
                                        <strong>{{ $errors->first('sector') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    Enviar Curriculo
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

This is the function that treats it:

public function envio(EnvioRequest $request){
        $usuarios=User::whereHas('experiencias',function($query) use ($request){
            $query->where('sector_empresa',$request->sector);
        })->get();

        if(count($usuarios)==0)
            return back()->with('message',['danger','No hay ningun usuario con experiencia en este sector']);
        else{
            $pdf = PDF::loadView('pdf.curriculo_sector', compact('usuarios'));
            Mail::to($request->email)->send(new Adjuntar($request->sector));
        }

        return back()->with('message',['success','Correo enviado.']);
    }

And this is the mail that the company will receive:

<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
    <title>Información de los usuarios con experiencia en {{$sector}}</title>
</head> 
<body>
    <p>Saludos, nos ponemos en contacto con vuestra empresa para mostraros una lista de candidatos a trabajar para vuestra empresa.</p><br>
    <p>Todos empleados que aparecen en el PDF adjunto tiene experiencia laboral en {{$sector}}.</p><br>
    <p>Atentamente, Bolsa Empleo San Fernando.</p>
</body>
</html>

This is the content of the PDF:

@extends('layouts.app')
<html lang="es">
<body>
    <?php
        $limite=count($usuarios);
    ?>

    @forelse($usuarios as $usuario)
        @include('pdf.datos_personales')
        @if($limite>1)
            <div style="page-break-after:always;"></div>
            {{$limite--}}
        @endif
    @empty
    Se ha producido un error...
    @endforelse
    <h1>Para más información, ponganse en contacto con {{\App\User::administrador}}</h1>
</body>
</html>

The content of 'pdf.personal data':

<?php
    $formaciones=$usuario->formacion;
    $idiomas=$usuario->idiomas;
    $experiencias=$usuario->experiencias;
?>

<font size="17" style="display: inline;">Datos del usuario</font> <img style="width: 60px; height: 60px;" align="right" src="{{url($usuario->ruta())}}"/>
    <table class="table table-hover table-striped">
        <thead>
            <tr>
                <th>Nombre</th>
                <th>Residencia</th>
                <th>Telefono</th>
                <th>DNI</th>
                <th>Vehiculo</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>{{ $usuario->name }} {{ $usuario->second_name }}</td>
                <td>{{ $usuario->direccion }} ({{ $usuario->localidad }}, {{ $usuario->provincia }})</td>
                <td>{{ $usuario->telefono }}</td>
                <td>{{ $usuario->dni }}</td>
                <td>
                    @if($usuario->vehiculo)
                        Es poseedor de vehiculo propio
                    @else
                        No posee vehiculo propio
                    @endif
                </td>
            </tr>
        </tbody>
    </table>

    <?php
        $forma=count($formaciones);
        $exp=count($experiencias);
        $idi=count($idiomas);
    ?>

    <hr>

    @if($forma>0)
        <h3>Cursos realizados</h3>
        <table class="table table-hover table-striped">
            <thead>
                <tr>
                    <th>Titulo</th>
                    <th>Grado</th>
                    <th>Centro</th>
                    <th>Finalización</th>
                </tr>
            </thead>
            @forelse($formaciones as $formacion)
                <tbody>
                    <tr>
                        <td>{{$formacion->titulo}}</td>
                        <td>{{$formacion->grado}}</td>
                        <td>{{$formacion->centro}}</td>
                        <td>
                            @if($formacion->finalizacion)
                                {{$formacion->anyio_finalizacion}}
                            @else
                                No
                            @endif
                        </td>
                    </tr>
                </tbody>
            @empty
                Se ha producido un error
            @endforelse
        </table>
    @else
        <h3>No ha hecho ningun curso formativo</h3>
    @endif

    <hr>

    @if($idi>0)
        <h3>Idiomas estudiados</h3>
            <table class="table table-hover table-striped">
            <thead>
                <tr>
                    <th>Idioma</th>
                    <th>Nivel de habla</th>
                    <th>Nivel de escritura</th>
                    <th>Titulo oficial</th>
                </tr>
            </thead>
            @forelse($idiomas as $idioma)
                <tbody>
                    <td>{{$idioma->idioma}}</td>
                    <td>{{$idioma->nivel_hablado}}</td>
                    <td>{{$idioma->nivel_escrito}}</td>
                    <td>{{$idioma->titulo_oficial}}</td>
                </tbody>
            @empty
                Se ha producido un error
            @endforelse
        </table>
    @else
        <h3>No ha estudiado ningun idioma</h3>
    @endif

    <hr>

    @if($exp>0)
        <h3>Experiencia Laboral</h3>
        <table class="table table-hover table-striped">
        <thead>
            <tr>
                <th>Puesto</th>
                <th>Función realizada</th>
                <th>Empresa</th>
                <th>Sector</th>
                <th>Fecha de inicio</th>
                <th>Fecha de finalización</th>
            </tr>
        </thead>
        @forelse($experiencias as $experiencia)
            <tbody>
                <tr>
                    <td>{{$experiencia->puesto}}</td>
                    <td>{{$experiencia->funcion_realizada}}</td>
                    <td>{{$experiencia->empresa}}</td>
                    <td>{{$experiencia->sector_empresa}}</td>
                    <td>{{$experiencia->mes_anyo_inicio}}</td>
                    <td>{{$experiencia->mes_anyo_fin}}</td>
                </tr>
            </tbody>
        @empty
            Se ha producido un error
        @endforelse
        </table>
    @else
        <h3>No tiene experiencia laboral</h3>
    @endif

    <hr><hr>

And now the crux of the matter, how do I have the PDF included in the email?

More information: Following documentation that I found, I have invented a PDF called Curriculum.php, I have left it in the Downloads folder, and I have executed the following:

public function envio(EnvioRequest $request){
        $usuarios=User::whereHas('experiencias',function($query) use ($request){
            $query->where('sector_empresa',$request->sector);
        })->get();

        if(count($usuarios)==0)
            return back()->with('message',['danger','No hay ningun usuario con experiencia en este sector']);
        else{
            $correo=Mail::to($request->email)->send(new Adjuntar($request->sector));
            return back()->with('message',['success','Correo enviado.']);
        }
    }

Also, I have updated the MailAdjuntar.php file:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class Adjuntar extends Mailable{
    use Queueable, SerializesModels;
    public $sector;

    public function __construct($sector){
        $this->sector=$sector;
    }

    public function build(){
        return $this->view('correo.adjunto')->attach('C:/Users/pcx/Downloads/Curriculo.pdf');
    }
}

Thanks to this, I have managed to attach a PDF for the first time. Now what remains is that the PDF is created and attached in a single command. One problem that I have is that if I want to create the PDF I must use return $pdf->download('Curriculo.pdf'); , but if I use a return, I end the program. How do I avoid this setback?

    
asked by Miguel Alparez 11.05.2018 в 17:00
source

1 answer

1

I refer you to the Laravel documentation:

link

And you can use in your Mailable, attach or attachData methods to attach the file.

    
answered by 11.05.2018 в 23:55