02 Jul

Laravel 4 and Laravel Excel to create export

A few weeks ago I jumped into Laravel and it’s been challenging. I’ve been working with PHP and JavaScript over the past countless years and before that ColdFusion and ASP. What has made the Laravel transition difficult for me is that most of the issues and resolutions posted expose the code but fail to explain where in the application it should go.

I know, I’ve read all about MVC structure and I’m starting to get it – but hopefully this might help others and if anyone has feedback or best practices – please reply!

For this project I have essentially users who have registered for an event and I call them attendees. I link to this
by dynamically pointing to /attendees/export?block_id=1. I have a table which contains regtypes – or types of registrants, for example: general and wait-list. The attexport function looks up those regtypes and generates a sheet of data for each as well a summary page with totals.

My route (routes.php):

Route::group(array('before' => 'auth'), function()
{
   Route::get('attendees/export', 'AttendeeController@export');
});

AttendeeController.php:

	public function export() 
	{
		if(Input::get('block_id')) {
			$attendees = new Attendee;
			$attendees->attexport(Input::get('block_id'));
		}
	}

attexport function from Attendee.php:

		public function attexport($block_id) {
			$report = Excel::create('export');
			$regtypes = Regtype::all();
		    $summary = $report->sheet('Summary', function($sheet) {
		    	
		    });
			foreach ($regtypes as $regtype) {
				$attendees = Attendee::where('block_id', '=', Input::get('block_id'))
					->where('regtype_id', '=', $regtype->id)
					->get();
				if($attendees->count() > 0)
				{
					$report->sheet($regtype->name, function($sheet) use ($regtype,$summary,$attendees) {
						$headers = $this->getColumnNames($attendees);

						// $attendees_array = array_merge((array)$headers, (array)$attendees->toArray());
						$attendees_array = $attendees->toArray();
						$sheet->with($attendees_array);
						$sheet->setStyle(array(
						    'font' => array(
						        'name'      =>  'Arial',
						        'size'      =>  12
						    )
						));
						$summary->prependRow(array(
						    $regtype->name, $attendees->count()
						));						
				    });
				}
			}
			// $summary->setCellValue($celltotal,$calc);
			$summary->setCellValue('B5','=SUM(B1:B4)');
			$summary->setCellValue('A5','Total Registered Attendees');
			$report->export('xls');

		}