Request file() is null in api Laravel - php

I have a route in my API right in Laravel for an iOS app that lets you upload images that I got form this tutorial https://www.codetutorial.io/laravel-5-file-upload-storage-download/
and when I tried to upload the file it turns null.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Fileentry;
use Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Response;
class FileEntryController extends Controller
{
public function add() {
$file = Request::file('filefield');
$extension = $file->getClientOriginalExtension();
Storage::disk('local')->put($file->getFilename().'.'.$extension, File::get($file));
$entry = new Fileentry();
$entry->mime = $file->getClientMimeType();
$entry->original_filename = $file->getClientOriginalName();
$entry->filename = $file->getFilename().'.'.$extension;
$entry->save();
return redirect('fileentry');
}
}
Route:
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->post('fileentry/add',array(
'as' => 'addentry',
'uses' => 'App\Http\Controllers\FileEntryController#add'
));
}
the user doesn't interact with the web page is all through the app
Other information that maybe the cause of the problem is that i'm using Postman to upload the image to the laravel app (Method: POST, through the binary section).

Try using form-data method from postman and add a parameter as file type.
Keep in mind that the key of the parameter must be equal to the key you're trying to get in backend. In your case it is filefield
$file = Request::file('filefield');

In your html form add this attribute
enctype="multipart/form-data"

Related

Laravel 8: How To Use Intervention Image Library Properly

I want to use Intervention Image library for my Laravel project, so I just installed it via Composer and added this line of code to config/app.php:
Intervention\Image\ImageServiceProvider::class,
And also this line was added to aliases part:
'Image' => Intervention\Image\Facades\Image::class,
Now at my Controller I coded this:
class AdminController extends Controller
{
protected function uploadImages($file)
{
$year = Carbon::now()->year;
$imagePath = "/upload/images/{$year}/";
$filename = $file->getClientOriginalName();
$file = $file->move(public_path($imagePath), $filename);
$sizes = ["300","600","900"];
Image::make($file->getRealPath())->resize(300,null,function($constraint){
$constraint->aspectRatio();
})->save(public_path($imagePath . "300_" . $filename));
}
}
But as soon as I fill my form to check if it's work or not, this error message pops up:
Error
Class 'App\Http\Controllers\Admin\Image' not found
Which means this line:
Image::make($file->getRealPath())->resize(300,null,function($constraint){
So why it returns this error while I've included it already in my project ?!
If you know, please let me know... I would really appreciate that.
Thanks
On config/app.php you need to add :
$provides => [
Intervention\Image\ImageServiceProvider::class
],
And,
$aliases => [
'Image' => Intervention\Image\Facades\Image::class
]
Now you can call use Image; on the top on your controller :
use Image;
class AdminController extends Controller
{
// ...
}

how to upload audio with a file in laravel?

making an api to upload multifile with an audio everything is working but audio file can't uploaded
and uploading with dd($request)->all
then it works
but while uploading with any condition its gives null value on every clientoriginalName ,extension,
how t fix this...
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use App\File;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Auth;
class FileController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'description' => 'nullable',
'file' => 'required|file|mimes:' . File::getAllExtensions() . '|max:' . File::getMaxSize(),
'Fileaudio' =>'nullable|mimes:audio/mpeg,mpga,mp3,wav,aac'
]);
//////////// All files //////////////////
$file = new File();
$title = $request->title;
$uploaded_file = $request->file('file');
$filename = $uploaded_file->getClientOriginalName();
$original_ext = $uploaded_file->getClientOriginalExtension();
$type = $file->getType($original_ext);
$filepath = $uploaded_file->storeAs('public/upload/files/',$filename);
$files = URL::asset('storage/upload/files/' . $filename);
$description = $request->description;
$user_id = Auth::user()->id;
/////////// Audio at null /////////////////
$Fileaudio = $request->file('audio');
$audioname = $Fileaudio->getClientOriginalName();
$audiopath =$Fileaudio->storeAs('public/upload/files/audio/', $audioname);
//return $audiopath;
dd($request->all());
}
}
and i am sending request to postman...
create a folder 'upload/files' inside storage/app/public , and /upload/files/audio
then run command : php artisan storage:link
this command will link your storage folder to public folder
update your code :
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use App\File;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
public function store(Request $request)
{
// validation
$this->validate($request, [
'title' => 'required',
'description' => 'nullable',
'file' => 'required|file|mimes:jpeg,jpg,png,gif|max:2048',
'audio' =>'nullable|file|mimes:audio/mpeg,mpga,mp3,wav,aac'
]);
// code for upload 'file'
if($request->hasFile('file')){
$uniqueid=uniqid();
$original_name=$request->file('file')->getClientOriginalName();
$size=$request->file('file')->getSize();
$extension=$request->file('file')->getClientOriginalExtension();
$name=Carbon::now()->format('Ymd').'_'.$uniqueid.'.'.$extension;
$imagepath=url('/storage/uploads/files/'.$name);
$path=$request->file('file')->storeAs('public/uploads/files/',$name);
}
// code for upload 'audio'
// handle multiple files
if(is_array($request->file('audio')))
{
$audios=array();
foreach($request->file('audio') as $file) {
$uniqueid=uniqid();
$original_name=$file->getClientOriginalName();
$size=$file->getSize();
$extension=$file->getClientOriginalExtension();
$filename=Carbon::now()->format('Ymd').'_'.$uniqueid.'.'.$extension;
$audiopath=url('/storage/upload/files/audio/'.$filename);
$path=$file->storeAs('/upload/files/audio',$filename);
array_push($audios,$audiopath);
}
$all_audios=implode(",",$audios);
}else{
// handle single file
if($request->hasFile('audio')){
$uniqueid=uniqid();
$original_name=$request->file('audio')->getClientOriginalName();
$size=$request->file('audio')->getSize();
$extension=$request->file('audio')->getClientOriginalExtension();
$filename=Carbon::now()->format('Ymd').'_'.$uniqueid.'.'.$extension;
$audiopath=url('/storage/upload/files/audio/'.$filename);
$path=$file->storeAs('public/upload/files/audio/',$filename);
$all_audios=$audiopath;
}
}
}
in your postman request :
add key : "file" for image file ,
"audio" for audio file
you can use these there sentences for upload any multipart
$file = $request->file;
$filename = time() . '.' . $file->getClientOriginalExtension();
$file->move('your-path', $filename);
and if you need to upload multi audios or images make sure your key on postman wrote like this
images[]
or
audios[]

Trying to get property 'POST /employee HTTP/1.1

I have created a laravel application to store employee data, but when I submit the form it gives me the following error, what should I do to avoid this problem. thanks
This is my EmployeeController store method
public function store(Request $request)
{
$this->validate($request,array(
'lastname'=>'required|max:60',
'firstname'=>'required|max:60',
'middlename'=>'required|max:60',
'address'=>'required|max:120',
'NIC'=>'required|max:10',
'city_id'=>'required|max:60',
'state_id'=>'required|max:60',
'mobile'=>'required|max:10',
'email'=>'required|max:60',
'postal_code'=>'required|max:10',
'birthdate'=>'required|date',
'date_hired'=>'required|date',
'department_id'=>'required|max:10',
));
$employee = new Employee();
$employee->lastname=$request->lastname;
$employee->firstname=$request->firstname;
$employee->middlename=$request->middlename;
$employee->address=$request->address;
$employee->NIC=$request->NIC;
$employee->city_id=$request->city_id;
$employee->state_id=$request->state_id;
$employee->mobile=$request->mobile;
$employee->email->$request->email;
$employee->postal_code=$request->postal_code;
$employee->birthdate=$request->birthdate;
$employee->date_hired=$request->date_hired;
$employee->department_id=$request->department_id;
$employee->save();
}
Form header
{!! Form::open(['route'=>'employee.store','class'=>'form-horizontal p-t-20']) !!}
Classes i used for the controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Department;
use Illuminate\Support\Facades\DB;
use App\Employee;
There is an error in your code.
$employee->email->$request->email;
This should be,
$employee->email = $request->email;
By the looks of it you are trying to validate the $request variable itself. Hence the Trying to get property POST
Should it not be...
$request->validate(array(
'lastname'=>'required|max:60',
'firstname'=>'required|max:60',
'middlename'=>'required|max:60',
'address'=>'required|max:120',
'NIC'=>'required|max:10',
'city_id'=>'required|max:60',
'state_id'=>'required|max:60',
'mobile'=>'required|max:10',
'email'=>'required|max:60',
'postal_code'=>'required|max:10',
'birthdate'=>'required|date',
'date_hired'=>'required|date',
'department_id'=>'required|max:10',
));
ErrorException: Trying to get property 'POST /Addpatients HTTP/1.1
This ERROR IS DUE to
when you difine your variable in any method Please check that you doest not define as below because it gives the error
$patients->address->$request->input('address');
The solution is of this is as below
$patients->address=$request->input('address');

Access same url with different Controller and method for API

I am currently working on API in laravel 5.6 and I would like versioning for APIs like v1 and v2.
my problem is I want to run one URL and access both API version, I am passing version number into HEADER and access API controller according to the version number. I am also using middle ware to check version number but not getting what I need.
Here is my web.php
Route::post('/api/getticktes/{id}', 'Api\v1\TicketController#show')->middleware('checkHeaderV1');
Header
version :- v1
version :- v2
My controller directory is
Controller
-Api
--v1
---TicketController.php
--v2
---TicketController.php
You can use this class, i have used it in my old project, may be it is not the efficient way but it will work
ApiVersion class
namespace App\Http;
use Illuminate\Http\Request;
class ApiVersion
{
protected static $valid_api_versions = [
1 => 'v1',
2 => 'v2'
];
protected static function get($request)
{
$allApiVersions = array_keys(self::$valid_api_versions);
$latestVersion = $allApiVersions[count($allApiVersions) - 1];
$apiVersion = $request->header('api-version', $latestVersion);
return in_array($apiVersion, $allApiVersions) ? $apiVersion : $latestVersion;
}
protected static function getNamespace($apiVersion)
{
return 'Api\\' . self::$valid_api_versions[$apiVersion];
}
public static function versionNamespace()
{
$request = Request::capture();
return $apiNamespace = ApiVersion::getNamespace(self::get($request));
}
}
Now use this middleware in api routes file for namespace
//API routes
$versionNameSpace = ApiVersion::versionNamespace();
Route::group(['middleware' => ['api'], 'namespace' => "{$versionNameSpace}"], function () {
});
Add api-version in your request header. The value should be 1 or 2 etc

Laravel 5.4 upload error with element-ui (vuejs)

I'm using element-ui components with VueJS. All is working great, except when I come to uploading a file using the file upload component:
Upload Controller:
<?php
namespace App\Http\Controllers\V1;
use Illuminate\Support\Facades\{Config, Log};
use Illuminate\Http\Request;
use App\Attachments as AttachmentClass;
use App\Http\Requests\AttachmentRequest;
use Facades\App\Attachments;
use App\Http\Controllers\Controller;
class AttachmentController extends Controller
{
/*
Upload a file for a given site
.................................................................. */
public function siteUpload (AttachmentRequest $request, $site_id)
{
// $this->request->file()
Log::info ('AttachmentController::fileUpload for site [' . $site_id . '] | request = ' . $request) ;
$attach = \App\Attachments::firstOrNew(['site_id' => $site_id]);
}
}
AttachmentRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AttachmentRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return ['fileName' => 'required', 'file' => 'mimes:pdf, jpg, jpeg, bmp, png|size:5000'];
}
}
However, when I upload an image to laravel, I get the following message:
POST http://localhost:8000/api/v1/upload/site/628 422 (Unprocessable Entity)
AttachmentsPanel.vue?8cf7:57 Fail Msg: Error: 422 {"error":"you did not send the required json in the body"}
I have a Log::info in the Laravel Controller that should display the file received.
However, it doesn't even get that far. The FormRequest guard seems to be throwing a 422 fit.
The error function of the upload component has some console.log entries, this is what the file portion returns:
I've chcked under Network Tools in Chrome and JSON data is being passed.
From the above, I don't think its the form upload control- since the data get passed successfully to Laravel.

Categories