How to POST data on database using Postman with laravel 9 - php

I try to POST data to database with "form-data" on "postman" with Laravel 9, and I try to return the data to JSON.
This is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\M_Barang;
class Utama extends Controller
{
public function index() {
return view('Utama');
}
public function store(Request $request) {
$this->validate($request, [
'file' => 'required|max:2048'
]);
$file = $request->file('file');
$nama_file = time()."_".$file->getClientOriginalName();
$tujuan_upload = 'data_file';
if ($file->move($tujuan_upload,$nama_file)) {
$data = M_Barang::create([
'nama_produk' => $request->nama_produk,
'harga' => $request->harga,
'gambar' => $nama_file
]);
$res['message'] = "succsess!";
$res['values'] = $data;
return response($res);
}
}
}
I get the following result:
This is my expected result:

You need to send data from raw section in JSON Format, and try to send your image in base64 format (because its very convenient way to store a image into file system via the API).
Example:{"profile_pic":"data:image/png;base64,iVBORw0KGgoAAAANSUh (base64 image string)"}
you can convert base64 image here https://www.base64-image.de/
and in Android and iOS has some libraries for converting image to base 64 while sending data to API
Welcome in Advance.

In Postman's headers section, you have to set Accept and content-type to application/json:
Image

Related

Sending file to api endpoint using guzzle and laravel

I'm trying to use guzzle to send a file to an api endpoint. WebsiteA (laravel) will send a file input to WebsiteB (laravel). The problem is, I'm getting a tmp path only in WebisteB when i check the request and not the whole file. I need to store the file in WebsiteB.
If i dd($request->file('file')) on WebsiteA it returns image below.
WebsiteA
public function postContent(Request $request) {
if($request->file){
$response = $this->guzzleClient()->post($this->archiving->url . config('archiving.api_post_file_content'),
[
'multipart' => [
[
'name' => 'file',
'contents' => $request->file('file'),
],
],
]
);
return $response->getBody();
}else{
return 'no file';
}
}
WebsiteB
public function storeContentFile(Request $request){
return $request->all(); //returns -> file: "C:\xampp\tmp\phpFEA3.tmp"
/* if($request->file){
$uploadedFiles=$request->file('file');
$file_name = time().'.'.$uploadedFiles->getClientOriginalName();
$uploadedFiles->move('media/content/', $file_name);
}
*/
//getting error getClientOriginalName() on string
}

how to read a google sheet from my drive without access token required in Laravel?

I am working on Laravel Project It require to add Google sheets & after add this it must be shareable at my site
this my Code.
When I open the link
http://localhost:8000/viewsheet/18ioWbPXjd1RM2wqJuJ0eFzkYAfC03OT9_X5tWJEV3uU/sheet/Phrasebook
from another browser, it gives me an error because I am not logged in
how I can make it shareable for all users without others login?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Sheets;
use Google;
class sheetview extends Controller
{
//
public function __invoke(Request $request, $spreadsheet_id, $sheet_id)
{
//// print_r($request);
// $rows = $request->user()
// ->sheets()
// ->spreadsheet($spreadsheet_id)
// ->sheet($sheet_id)
// ->get();
$user = $request->user();
$token = [
'access_token' => $user->access_token,
'refresh_token' => $user->refresh_token,
'expires_in' => $user->expires_in,
'created' => $user->updated_at->getTimestamp(),
];
// all() returns array
$values = Sheets::setAccessToken($token)- >spreadsheet($spreadsheet_id)->sheet($sheet_id)->all();
print_r($values);
///$headers = $rows->pull(0);
// return view('sheets.viewsheet')->with(compact('headers', 'rows'));
}
}

Laravel form request validation priority

In my Laravel 5.6 app, I have a controller with a store method:
use Intervention\Image\Facades\Image as ImageHandler;
public function store(StoreFoo $request)
{
if ($request->hasFile('image')) {
$toResize = ImageHandler::make($request->validated()->file('image')->getRealPath());
}
}
My StoreFoo class validates that the image field is an image:
public function rules()
{
return [
'image' => 'image'
];
}
I would expect that when I try to upload a file which is not an image, the validator would catch it and return an error. Instead the code inside the store method is run, which produces an "Unsupported image type" exception from Intervention.
Why does the validator not catch this beforehand, and how can I make it work this way?
Try this in your request file:
'image' => 'nullable|file|mimes:jpeg,png,jpg',
Of course, feel free to add whatever other mimes you will accept.

Request file() is null in api Laravel

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"

Laravel displaying base64 image

How can I send e-mail with attached image if I receive the data in base64 format?
Here is mail template:
<h1>You got mail from - {{$user->name}}</h1>
<h2>Date:</h2>
<p>{{$post->created_at}}</p>
<h2>Message:</h2>
<p>{{$post->body}}</p>
<img src="data:image/png;base64, {{$image}}">
<div>
</div>
And the logic:
public function createPost()
{
$user = JWTAuth::toUser();
$user->posts()->create(['user_id' => $user->id, 'body' => Input::get('comment.body')]);
Mail::send('mail.template', [
'image' => Input::get('image'),
'user' => $user,
'post' => Post::where('user_id', $user->id)->get()->last(),
], function ($m) use ($user) {
$m->from('xyz#app.com', 'XYZ');
$m->to('xyz#gmail.com', $user->name)->subject('Subject');
});
}
From this I only get mail with full base64 string...img tag gets ignored
Attachments
To add attachments to an email, use the attach method within the
mailable class' build method. The attach method accepts the full path
to the file as its first argument:
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.orders.shipped')
->attach('/path/to/file');
}
More information here (for Laravel 5.3).
I hope, it will be helpful.
The solution I came up with is to save the image first in order to attach it as Viktor suggested although I don't have Laravel 5.3. so the method is somehow different.
User may or may not send the picture, so the method is as follows:
$destinationPath = null;
if($request->has('image')){
// save received base64 image
$destinationPath = public_path() . '/uploads/sent/uploaded' . time() . '.jpg';
$base64 = $request->get('image');
file_put_contents($destinationPath, base64_decode($base64));
}
And then attach the saved image to the mail:
Mail::send('mail.template', [
'user' => $user,
'post' => Post::where('user_id', $user->id)->get()->last(),
], function ($m) use ($user) {
$m->from('xyz#app.com', 'XYZ');
$m->to('xyz#gmail.com', $user->name)->subject('Subject');
if($request->has('image')){
$m->attach($destinationPath);
}
});
The mail template:
<h1>You got mail from - {{$user->name}}</h1>
<h2>Date:</h2>
<p>{{$post->created_at}}</p>
<h2>Message:</h2>
<p>{{$post->body}}</p>

Categories