jasonb's avatar

Saving a file in a form.

OK I am a little confused. I have a route where I can process a file upload that stores correctly. But when I want to process a complete form with a file I am lost. {code} Route::post('/forms/store', 'FormsController@store'){ request()->file('pic1')->store('pics'); }; [/code]

I know this is written incorrectly. But I am not sure how to make the two work together.

0 likes
20 replies
jasonb's avatar

So here is the idea. I want to use the same controller to handle the storage of the form data to the sql database and store the file that is being sent.

public function store(Request $request){
      //  return $request->all();
        $form = new Form;
        $form->title = $request->title;
        $form->body = $request->body;
        $form->pic1 = $request->pic1;
        $form->save();
        $request()->file('pic1')->store('pics');


    }
bashy's avatar

What exactly do you want to save? You can store the file and return the filename it has saved it as and add that into the database?

jasonb's avatar

The form:

  <form method="post" action="/forms/store" enctype="multipart/form-data">
                            <input type="hidden" name="_token" value="{{ csrf_token() }}">
                            <div class="form-group">
                                <label for="title" class="control-label">Title</label>
                                <input class="form-control" name="title"></input>

                            </div>
                            <div class="form-group">
                                <label for="body" class="control-label">Content Body</label>
                                <textarea class="form-control" name="body"></textarea>

                            </div>
                            <div class="form-group">
                                <label for="pic" class="control-label">Upload Picture</label>
                                <label class="btn btn-default btn-file">
                                    Browse <input type="file"  name="pic1" style="display: none;">
                                </label>

                            </div>




                            <div class="form-group">
                                <button class="btn btn-primary" type="submit"><i class="fa fa-sticky-note-o" aria-hidden="true"></i> Add Form</button>
                            </div>
                        </form>

The controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Form;
use DB;
/**
 * Create a new controller instance.
 *
 * @return void
 */


class FormsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth'); // This will require basic authentication with Larvel Auth.
    }
    //
    public function index(){

        //$forms = DB::table('forms')->get();
        $forms = form::all();

        return view('forms.index', compact('forms'));

    }

    public function show(Form $form){
//        $form = Form::find($id); // old way not needed with type hinting
      return view('forms.show', compact('form'));

    }

    public function newform(){
//return "Hello";
        return view('forms.new');

    }

    public function store(Request $request){
      //  return $request->all();
        $form = new Form;
        $form->title = $request->title;
        $form->body = $request->body;
        $form->pic1 = $request->pic1;
        $form->save();
        $request->file('pic1')->storeas('pics');



    }
    
}

The Route:

   Route::post('/forms/store', 'FormsController@store');
jasonb's avatar

So I want to save the file name into the database and I want to save the actual file in a folder called pics in the storage folder

bashy's avatar

I remember seeing in the docs for the store() and storeAs() and it returns the filename? If so, you can do the following;

Don't need storeAs() since you're wanting to automatically generate the filename it uses?

public function store(Request $request) {
    $path = $request->file('pic1')->store('pics');
    
    $form = new Form;
    $form->title = $request->title;
    $form->body = $request->body;
    $form->pic1 = $path;
    $form->save();
}
jasonb's avatar

That gives us: BadMethodCallException in Macroable.php line 74: Method store does not exist.

jasonb's avatar

So when I run:

 public function store(Request $request){
     
        $path = $request->pic1->store('pics');
        return $path;




    }

I get: BadMethodCallException in Macroable.php line 74: Method store does not exist.

This is so strange.

This might be helpful: in Macroable.php line 74 at UploadedFile->__call('store', array('pic1')) in FormsController.php line 46 at UploadedFile->store('pic1') in FormsController.php line 46 at FormsController->store(object(Request)) at call_user_func_array(array(object(FormsController), 'store'), array(object(Request))) in Controller.php line 80 at Controller->callAction('store', array(object(Request))) in ControllerDispatcher.php line 146 at ControllerDispatcher->call(object(FormsController), object(Route), 'store') in ControllerDispatcher.php line 94 at ControllerDispatcher->Illuminate\Routing{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52 at Pipeline->Illuminate\Routing{closure}(object(Request)) in Authenticate.php line 28 at Authenticate->handle(object(Request), object(Closure)) at call_user_func_array(array(object(Authenticate), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136 at Pipeline->Illuminate\Pipeline{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32 at Pipeline->Illuminate\Routing{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103 at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 96 at ControllerDispatcher->callWithinStack(object(FormsController), object(Route), object(Request), 'store') in ControllerDispatcher.php line 54 at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\FormsController', 'store') in Route.php line 174 at Route->runController(object(Request)) in Route.php line 140 at Route->run(object(Request)) in Router.php line 724 at Router->Illuminate\Routing{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52 at Pipeline->Illuminate\Routing{closure}(object(Request)) in VerifyCsrfToken.php line 64 at VerifyCsrfToken->handle(object(Request), object(Closure)) at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136 at Pipeline->Illuminate\Pipeline{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32 at Pipeline->Illuminate\Routing{closure}(object(Request)) in ShareErrorsFromSession.php line 49 at ShareErrorsFromSession->handle(object(Request), object(Closure)) at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136 at Pipeline->Illuminate\Pipeline{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32 at Pipeline->Illuminate\Routing{closure}(object(Request)) in StartSession.php line 64 at StartSession->handle(object(Request), object(Closure)) at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136 at Pipeline->Illuminate\Pipeline{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32 at Pipeline->Illuminate\Routing{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37 at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136 at Pipeline->Illuminate\Pipeline{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32 at Pipeline->Illuminate\Routing{closure}(object(Request)) in EncryptCookies.php line 59 at EncryptCookies->handle(object(Request), object(Closure)) at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136 at Pipeline->Illuminate\Pipeline{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32 at Pipeline->Illuminate\Routing{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103 at Pipeline->then(object(Closure)) in Router.php line 726 at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 699 at Router->dispatchToRoute(object(Request)) in Router.php line 675 at Router->dispatch(object(Request)) in Kernel.php line 246 at Kernel->Illuminate\Foundation\Http{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52 at Pipeline->Illuminate\Routing{closure}(object(Request)) in CheckForMaintenanceMode.php line 44 at CheckForMaintenanceMode->handle(object(Request), object(Closure)) at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136 at Pipeline->Illuminate\Pipeline{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32 at Pipeline->Illuminate\Routing{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103 at Pipeline->then(object(Closure)) in Kernel.php line 132 at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99 at Kernel->handle(object(Request)) in index.php line 54

JoolsMcFly's avatar

Weird.

Can you add this:

if ($request->hasFile('pic1') && $request->file('pic1')->isValid()) {
 die($request->pic1);
}
else {
  die("invalid file");
}
jasonb's avatar

this is what came out:

/Applications/MAMP/tmp/php/phpbnsVa2
JoolsMcFly's avatar

You're on 5.2 I guess.

$request->file('pic1')->move(public_path('pics'));

You can also pass a name as second param to move.

jasonb's avatar

Dang I thought I was on 5.3 /** * The Laravel framework version. * * @var string */ const VERSION = '5.2.45';

jasonb's avatar

JoolsMcFly, FatalErrorException in FormsController.php line 46: Call to a member function move() on a non-object

JoolsMcFly's avatar

lol WTF is up with your setup? ^^

How about:

$file = Input::file('pic1');
$file->move(public_path('pics'));

If that doesn't work you can fall back to good ole PHP move_uploaded_file

jasonb's avatar

OK Just walking through the example Jeff does here: https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/12 What's New in Laravel 5.3: Super Simple File Uploading

I follow along and when I try to store the file I get this: FatalErrorException in routes.php line 19: Call to a member function store() on null

Route:

<?php

Route::get('/', function () {
    return view('welcome');
});

Route::post('avatars', function () {
   request()->file('avatar')->store('avatars');
    return back();
});

here is the welcome blade:

<!DOCTYPE html>
<html>
    <head>
        <title>Laravel</title>

        <link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">

        <style>
            html, body {
                height: 100%;
            }

            body {
                margin: 0;
                padding: 0;
                width: 100%;
                display: table;
                font-weight: 100;
                font-family: 'Lato';
            }

            .container {
                text-align: center;
                display: table-cell;
                vertical-align: middle;
            }

            .content {
                text-align: center;
                display: inline-block;
            }

            .title {
                font-size: 96px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="content">
                <div class="title">Avitars</div>
                <form method="POST" action="avatars" enctype="multipart/form-data">
                    {{ csrf_field()}}
                    <input type = "file" name="avitar"></input>
                    <button type="submit">Save Avatar</button>

                </form>
            </div>
        </div>
    </body>
</html>

Pretty straight forward.

The full dump:

in routes.php line 19 at FatalErrorException->__construct() in HandleExceptions.php line 133 at HandleExceptions->fatalExceptionFromError() in HandleExceptions.php line 118 at HandleExceptions->handleShutdown() in HandleExceptions.php line 0 at RouteServiceProvider->{closure:/Users/jbrashear/tastycoders-DEV/dantest/avatars/app/Http/routes.php:18-20}() in Route.php line 158 at call_user_func_array:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Routing/Route.php:158}() in Route.php line 158 at Route->runCallable() in Route.php line 137 at Route->run() in Router.php line 724 at Router->Illuminate\Routing{closure}() in Pipeline.php line 52 at call_user_func:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:52}() in Pipeline.php line 52 at Pipeline->Illuminate\Routing{closure}() in VerifyCsrfToken.php line 64 at VerifyCsrfToken->handle() in Pipeline.php line 136 at call_user_func_array:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:136}() in Pipeline.php line 136 at Pipeline->Illuminate\Pipeline{closure}() in Pipeline.php line 32 at call_user_func:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:32}() in Pipeline.php line 32 at Pipeline->Illuminate\Routing{closure}() in ShareErrorsFromSession.php line 49 at ShareErrorsFromSession->handle() in Pipeline.php line 136 at call_user_func_array:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:136}() in Pipeline.php line 136 at Pipeline->Illuminate\Pipeline{closure}() in Pipeline.php line 32 at call_user_func:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:32}() in Pipeline.php line 32 at Pipeline->Illuminate\Routing{closure}() in StartSession.php line 64 at StartSession->handle() in Pipeline.php line 136 at call_user_func_array:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:136}() in Pipeline.php line 136 at Pipeline->Illuminate\Pipeline{closure}() in Pipeline.php line 32 at call_user_func:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:32}() in Pipeline.php line 32 at Pipeline->Illuminate\Routing{closure}() in AddQueuedCookiesToResponse.php line 37 at AddQueuedCookiesToResponse->handle() in Pipeline.php line 136 at call_user_func_array:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:136}() in Pipeline.php line 136 at Pipeline->Illuminate\Pipeline{closure}() in Pipeline.php line 32 at call_user_func:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:32}() in Pipeline.php line 32 at Pipeline->Illuminate\Routing{closure}() in EncryptCookies.php line 59 at EncryptCookies->handle() in Pipeline.php line 136 at call_user_func_array:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:136}() in Pipeline.php line 136 at Pipeline->Illuminate\Pipeline{closure}() in Pipeline.php line 32 at call_user_func:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:32}() in Pipeline.php line 32 at Pipeline->Illuminate\Routing{closure}() in Pipeline.php line 103 at call_user_func:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:103}() in Pipeline.php line 103 at Pipeline->then() in Router.php line 726 at Router->runRouteWithinStack() in Router.php line 699 at Router->dispatchToRoute() in Router.php line 675 at Router->dispatch() in Kernel.php line 246 at Kernel->Illuminate\Foundation\Http{closure}() in Pipeline.php line 52 at call_user_func:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:52}() in Pipeline.php line 52 at Pipeline->Illuminate\Routing{closure}() in CheckForMaintenanceMode.php line 44 at CheckForMaintenanceMode->handle() in Pipeline.php line 136 at call_user_func_array:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:136}() in Pipeline.php line 136 at Pipeline->Illuminate\Pipeline{closure}() in Pipeline.php line 32 at call_user_func:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:32}() in Pipeline.php line 32 at Pipeline->Illuminate\Routing{closure}() in Pipeline.php line 103 at call_user_func:{/Users/jbrashear/tastycoders-DEV/dantest/avatars/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:103}() in Pipeline.php line 103 at Pipeline->then() in Kernel.php line 132 at Kernel->sendRequestThroughRouter() in Kernel.php line 99 at Kernel->handle() in index.php line 54 at {main}() in index.php line 0

JoolsMcFly's avatar

You said you were using 5.2. Jeffrey's example is for 5.3.

jasonb's avatar

I was. I upgraded my php and created a new instance of the laravel install from scratch. I am at 5.3 and using Jeffs example.

bashy's avatar

I have a 5.3 install and I'm currently working with uploads. I've just done this and it's working as expected.

use Illuminate\Http\Request;

// method here with `Request $request`
$file = $request->file('file');
$path = $file->storeAs('documents', str_random(32).'-project-'.$project_id);

Please or to participate in this conversation.