How can I pass image file from Laravel to Express using Graphql? - laravel

I have a laravel project and my goal is to pass an image file from laravel to my express project, so that my graphql can save the name of my image file after
successfully renaming the image and uploading it in my express project.
At the moment, I am using \Softonic\GraphQL to query data from my express project. Example:
public function getUsers()
{
$client = \Softonic\GraphQL\ClientBuilder::build('http://localhost:3002/graphql');
$query = '
query GetUsers($sort:[[String!]!]!){
users(perPage:10, page: 1, sort: $sort){
users{
email
}
}
}
';
$var = [
'sort' => "email"
];
$response = $client->query($query, $var);
return $response->getData();
}
How should i implement it when uploading an image ? my current code looks like this ..
public function updateImg(Request $request)
{
$client = \Softonic\GraphQL\ClientBuilder::build('http://localhost:3002/graphql');
$query = '
mutation updateImage(id:ID!, $image: Upload!){
updateImage(id:1, image: $image){
users{
email
}
}
}
';
$var = [
'image' => $request->file('uploadImg');
];
$response = $client->query($query, $var);
return $response->getData();
}
On my express, when i inspect my image in console.log(), it returns empty.
I am not sure if the way im doing is correct or if it is even achievable.

One way to add support for uploading files to GraphQL is to add multipart form request support through this specification by Jayden Seric. He also provides an implementation project for certain environments. However, I have only tried and tested this with apollo-client and apollo-server-express.

Related

Importing generated csv from Laravel into Google Sheets

I'm trying to import an automatically generated csv into Google Sheets using this as cell value:
=importData("https://example.com/reports/some-report")
When I try importData on a static file on the server everything works as expected (like =importData("https://example.com/storage/some-static-report.csv") )
..but when I generate the file on the fly () I get a #N/A in the cell; "Resource at url not found." error.
This is the Laravel code to generate the csv:
public function downloadReportsAsCSV(Request $request) {
$list = [];
$list[] = ['timestamp', 'id', 'value'];
// ... fill the list with data here
$callback = function() use ($list) {
$out = fopen('php://output', 'w+');
// Write CSV lines
foreach ($list as $line) {
fputcsv($out, $line);
}
fclose($out);
};
$name = 'somereport.csv';
$headers = [
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename='. $name,
];
return response()->stream($callback, 200, $headers);
}
The route to this method is public so authentication is not a problem in this case.
When I call https://example.com/reports/some-report in a browser it downloads the file (as somereport.csv), but somehow Google Sheeds can't handle it the way I expect it to.
Any ideas on how to make this work?
It seems to be working after all, it's just that Google Sheets apparently needed quit some time before updating the field (at least a couple of minutes).
If anyone has any idea how to trigger Google Sheets to update the data immediately I'd sure like to know.

update profile in laravel API for mobile apps

I want to build an api for mobile apps. for now, i want to create an edit profile api. but i dont know how to store an image, if user wants to upload their avatar.
Here is my code:
public function profileedit($id, Request $request){
$users = user::find($id);
$users->name = $request->firstName;
$users->thumbnail = $request->avatar;
$users->save();
$data[] = [
'id'=>$users->uid,
'name'=>$users->name,
'avatar'=>$users->thumbnail,
'status'=>200,
];
return response()->json($data);
}
how to put the $request->avatar into my project storage, and show it in url form (my project is already uploaded on the server)
The easiest way to store files in Laravel is this.
use Illuminate\Support\Facades\Storage;
public function profileedit($id, Request $request){
//validator place
$users = user::find($id);
$users->name = $request->firstName;
$users->thumbnail = $request->avatar->store('avatars','public');
$users->save();
$data[] = [
'id'=>$users->uid,
'name'=>$users->name,
'avatar'=>Storage::url($users->thumbnail),
'status'=>200,
];
return response()->json($data);
}
but as you probably know, you should run php artisan storage:link command to generate storage shortcut in public directory.
for security reason you can use validator to let only image file store. in this example I limited file to all image types with maximum 4MB size
$request->validate([
'avatar' => 'required|image|max:4096',
]);
for more information these are document links.
File Storage
Validation

Laravel: Database is not storing my image but showing me only array

I am new to Laravel. I have been trying to save an image to the database. Here is my controller method that I am trying for storing the image
public function store(Request $request){
//validation for form
$validate= $request->validate([
'name' => 'required|min:2|max:140',
'position' => 'required|min:2|max:140',
'salary' => 'required|min:2|max:140',
'joining_date' => ''
]);
//saving form
if($validate){
$employee=new Employee;
$employee->name =$request->input('name');
$employee->company_name =$request->input('company_name');
$employee->position =$request->input('position');
$employee->salary =$request->input('salary');
$employee->joining_date =$request->input('joining_date');
$employee->user_id= auth()->user()->id;
//image saveing method
if($request->hasFile('image')){
$image= $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
Employee::make($image)->resize(300, 300)->save( public_path('/employee/images/' . $filename ) );
$employee->image= $filename;
}else{
return $request;
$employee->image= '';
};
$employee->save();
//redirecting to Employee list
return redirect('/employee/details')->with('success','Employee Added');
}
I could save the form while there was no image and redirect it to the details page. but now when I try with the image, instead of saving it and redirecting to the details route, it returns me to the array of row of database like this:
{
"_token": "FPHm9AKuEbRlqQnSgHhjPnCEKidi2xr0usgp7RoW",
"name": "askfjlk",
"company_name": "laksjsflkj",
"position": "lkasjfkl",
"salary": "35454",
"joining_date": "4654-05-06",
"image": "testing.png"
}
What did I do wrong here? please help me out this newb.
You are returning $request object and Laravel does automatic JSON response.
if ($request->hasFile('image')){
// image storing logic which obviously is never started because expression above is false
} else {
return $request; // There is your problem
$employee->image= '';
};
You need to check why you are getting false on $request->hasFile('image').
Also, one tip because you are new to Laravel:
// When you are accessing to $request object you can use dynamic propertes:
$employee->company_name = $request->input('company_name');
// is the same as
$employee->company_name = $request->company_name;
You can check it there: Laravel docs in the section: Retrieving Input Via Dynamic Properties

deleteFileAfterSend Laravel response doesn't delete file in tests

I an have laravel 5.5 App.
I'm trying to make a test for download PDF with laravel snappy.
So far I have in my CheckTest.php one function:
public function testPrintCheck(){
$check = $this->createCheck();
$route ="/api/checks/print/$check->id";
$response = $this->get($route);
$this->assertEquals($response->headers->get('content-type') , 'application/pdf');
$response->assertStatus(200);
}
In my controller I have:
public function printCheck(Request $request, Check $check){
$pdf = \PDF::loadView("pdf.check");
$file= storage_path(). "/app/checks/$check->id.pdf";
$pdf->save($file);
$headers = array(
'Content-Type: application/pdf'
);
return response()->download($file, "check_n_$check->id.pdf", $headers)->deleteFileAfterSend(true)->setStatusCode(200);
}
The current test works but I expect to delete file that I have create after download (with deleteFileAfterSend(true)) , but the file is not deleted.
So if I add the assert that file not exist it fails.
There is a possible solution to this according to the issue created not so long ago on github:
https://github.com/laravel/framework/issues/36286
Working on Laravel 8.24
Basically we need to force sending file contents, which then triggers file deletion
public function test(): void
{
$response = $this->get('url/to/download');
// Here the file is not deleted yet
$response->sendContent();
// Here the file is deleted
}

Laravel password recovery template

I have the following code which sends a passowrds recovery mail:
public function recovery(Request $request)
{
$validator = Validator::make($request->only('email'), [
'email' => 'required'
]);
if($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject(Config::get('boilerplate.recovery_email_subject'));
});
switch ($response) {
case Password::RESET_LINK_SENT:
return $this->response->noContent();
case Password::INVALID_USER:
return $this->response->errorNotFound();
}
}
Which I found out uses the following template: resources/views/auth/emails/password.php
which is an empty file.
How I can access the token from this template?
Isn't there any built-in view to use from laravel?
The function in your questions doesn't return a view.
Also, I'm unfamiliar with that path to the view that is in your question. Which version of Laravel are you using?
Anyhow, you can get the reset token from the DB, just like any other value in the DB. E.g. from a controller that is returning a view:
$user = User::find(Auth::id());
$remeber_token = $user->remember_token;
return view('to_your_view.blade.php', compact('remember_token');
And then in the view file:
{{ $remember_token }}
This will output it, no need to use echo or anything.
But, again, the function you pasted into your question is not a function that is returning a view, so I'm not sure where to tell you to put the above code.
As for your questoin about Laravel having an in-built view for 'this', in Laravel 5.3, at least, the view I assume you want will be within `resources/views/auth/passwords/'.

Resources