marked-down
marked-down

Reputation: 10418

Using laravel, how can I create a dynamic file download?

I'm converting one of my current sites to a MVC pattern with Laravel, and I'm stuck on how to manage one feature: dynamic calendar downloads.

Currently, when a user navigates to calendar.php?var=1, a calendar.ics file is prepared to be download, and the user is prompted automatically:

header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename='.$calData->filename($calData->filename).'.ics'); 


$calData = new CalendarBuilder($_GET['foo']);

$ical = "BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN\r\n";

        $ical .= "BEGIN:VEVENT
UID:" . md5(uniqid(mt_rand(), true)) . "@foo.com
DTSTAMP:" . gmdate('Ymd').'T'. gmdate('His') . "Z
DTSTART:".$calData->eventStart($calData->foobar)."
DTEND:".$calData->eventEnd($calData->foobaz)."
SUMMARY:".$calData->summary($calData->fooboo)."
LOCATION:".$calData->location($calData->foofaa)."
DESCRIPTION:".$calData->description($calData->fi)."
END:VEVENT\r\n";

$ical .= "END:VCALENDAR";

echo $ical;
exit;

However, now I want a user to be able to navigate to calendar/{slug} and for a download response to be sent immediately. However, using Laravel, I can't see any way to do so. For example, I could set up a route:

Route::get('calendar/{slug}', array(
    'as' => 'calendar.get',
    'uses' => 'CalendarController@get'
));

And that could go to my controller:

class CalendarController extends BaseController {

    // GET Specific Calendar
    public class get() {
        // some logic
        return Response::download();
    }
}

But using the Response::download() method, there doesn't appear to be any way to generate a file dynamically, since the arguments of that method are:

Response::download($pathToFile, $name, $headers);

It seems to require a static, pre-existing file. What is the best way to implement the functionality I have currently while using Laravel's MVC architecture?

Upvotes: 3

Views: 3882

Answers (1)

ionescho
ionescho

Reputation: 1400

I was just working on something similar.

Here is how it worked for me:

return Response::make($ical)->header("Content-type","text/calendar; charset=utf-8")->header("Content-disposition","attachment; filename=\"".$calData->filename($calData->filename)."\"");

P.S. : I know it's kind of late but there should be an answer here for anybody else seeking.

Upvotes: 6

Related Questions