0
votes

i am trying to make a dynamic list of downwload links in my view but i am not quite sure how to return the response::download for each link

this is what i tried...

1.-My View

@extends('layouts.main')
@section('content')
    @foreach($files as $file)   
        <div class = "row fondue">
                <h3><div class="col-md-12"><b><?php echo link_to("/home/download",$file->name,$file)?> </b></div></h3>                  
        </div>  

    @endforeach

@stop

im not sure if i can send a third parameter to the link_to

2.-My Route

Route::get('/home/download','HomeController@downloadfile')->before('auth');

3.-My function in the controller

public function downloadfile($file)
{
    return Response::download($file->route);
} 

the view seems normal but when clicking on the links im getting the error:

"Missing argument 1 for HomeController::downloadfile()"

so my doubt is....how can i send the argument missing from the link in my view to my controller?

also...there is a better way to do that?

2

2 Answers

1
votes

The error you get is a complaint that your method downloadfile() wants a $file passed to it, but your route doesn't give it one. So you'll want to update your route with a parameter, like this:

Route::get('/home/download/{$file}','HomeController@downloadfile')->before('auth');

However, since we're going to pass things to it, I'd suggest naming it as well - it'll make things easier later on:

Route::get('/home/download/{$file}', [
    'as' => 'download.file',
    'uses' => 'HomeController@downloadfile']
)->before('auth');

Next, as you guessed yourself, you'll need to update the linking. The link_to() helper function does not take a parameters array, which is why we are now using named routes, and therefore we can now use link_to_route() instead - let's take a look at the documentation:

echo link_to_route('route.name', $title, $parameters = array(), $attributes = array());

That means we can rewrite. And also, don't forget that you're using Blade - no need for the php tags. So we end up with this:

{{ link_to_route('download.file', $file->name, [$file->id]) }}

Finally, I don't know your application logic, but your controller method will probably need to start by finding the file whose id you are now providing. Here's one example, but it really depends upon how your app is looking.

public function downloadfile($id)
{
    $file = SomeFileModel::findOrFail($id);
    return Response::download($file->route);
}

Hope that helps! Good luck.

0
votes

change link_to function to

link_to("/home/download/$file->name",$file->name)

change your route to:

Route::get('/home/download/{name?}','HomeController@downloadfile')->before('auth');

after that you'll be able to see argument in a downloadfile function