MoFish's avatar

request->all() query

Hi,

I am uploading a file and trying to store the filename into my database table.

The value which is going into my database table is a temp file e.g. \tmp\phpEA04.tmp

Which must be coming straight from the 'file' upload input box and not using my specified one below.

Am i correct in saying that if i do a $request->all that I can specify fields individually?

$result->create($request->all() + [
    'user_id' => Auth::user()->id,
    'file' => $file
]);

I also experimented with guarded/fillable in moy model, but could not get the desired result.

class Asset extends Model
{
    use HasFactory;
    protected $guarded = [];
}
0 likes
8 replies
tykus's avatar

You need to store the UploadedFile instance

$result->create($request->all() + [
    'user_id' => Auth::user()->id,
    'file' => $request->file('file')->store(/* directory */),
]);
johnDoe220's avatar
Level 8
public function store(Request $request)
{
	Post::create([
			'user_id' => auth()->user()->id,
			'file' => $request->file->store('posts')
		]);
}
<form method = "post" action="{{ route('posts.store') }}" enctype="multipart/form-data">
	<input type="file" name="file">
	<button type="submit"></button>
</form>
MoFish's avatar

The code is storing the following value \tmp\php5786.tmp in my database.

I would like it to store the original file name e.g. hello.txt

        $result->create($request->all() + [
            'user_id' => Auth::user()->id,
            'file' =>  $request->file('file')->store('assets'),
        ]);

Is this because i'm using request->all() instead of specifying the fields individually via create?

Or do I need to use getClientOriginalName

MoFish's avatar

@johnDoe220 Yes i have that

<form method="POST" action="{{route('asset.store')}}" enctype="multipart/form-data">

MoFish's avatar

I tested adding "hello" as a string when I perform a create; however it still sets tmp\phpE79D.tmp as the filename in the table. It must be something to do with the request->all() automatically populating file with file.

        $result->create($request->all() + [
            'user_id' => Auth::user()->id,
            'file' =>  "hello",
        ]);
MoFish's avatar

I ended up calling the file input field upload and then using the value of upload to populate the file field.

That appears to work.

$request->upload->move(public_path('assets'), $request->upload->getClientOriginalName());
$result = new Asset;
$result->create($request->all() + [
    'user_id' => Auth::user()->id,
    'file' =>  $request->upload->getClientOriginalName()
]);    

Please or to participate in this conversation.