Laravel/Lumen file response - laravel-5

I need to stream file content (such as images and other mime types) from a Lumen resource server to a Laravel client server. I know in Laravel I can use:
$headers = ['Content-Type' => 'image/png'];
$path = storage_path('/mnt/somestorage/example.png')
return response()->file($path, $headers);
However, the file method is absent in Laravel\Lumen\Http\ResponseFactory.
Any suggestions are very welcome.

In Lumen you can use Symfony's BinaryFileResponse.
use Symfony\Component\HttpFoundation\BinaryFileResponse
$type = 'image/png';
$headers = ['Content-Type' => $type];
$path = '/path/to/you/your/file.png';
$response = new BinaryFileResponse($path, 200 , $headers);
return $response;
You can find the documentation here.

There is a function in Lumen:
https://lumen.laravel.com/docs/8.x/responses#file-downloads
<?php
namespace App\Http\Controllers;
use App\Models\Attachment;
use Illuminate\Http\Request;
class AttachmentController extends AbstractController
{
/**
* Downloads related document by id
*/
public function attachment(Request $request)
{
$path = "path/to/file.pdf";
return response()->download($path);
}
}

Related

How to return image in Laravel 6?

I have this code:
public function showImage($id) {
$item = File::find($id);
return response()->file($item->file_name_and_path);
}
$item->file_name_and_path contains the following:
files/2020/04/29/myfile.jpeg
Now I always get a FileNotFoundException.
The image file is on local driver in this path:
{laravel root}/storage/app/files/2020/04/29/myfile.jpeg
How can I get the correct local path or simply return the image file with image HTTP headers?
You could use the Storage facade for this:
use Illuminate\Support\Facades\Storage;
public function showImage($id) {
$item = File::find($id);
return Storage::response($item->file_name_and_path);
}
As you can see here, it will add the following headers to the response:
'Content-Type'
'Content-Length'
'Content-Disposition'

How to serve the data returned from laravel Storage::disk('private')->get($file) as PDF

My question is about the problem in link below :
Understanding file storage and protecting contents Laravel 5
I need to use the same method mentioned in above example but instead of an image I need to provide a download link for PDF file or a link to open PDF file in browser and I can't do that because, as mentioned in above example's comments The Storage::disk('private')->get($file) returns the CONTENT of the file NOT the URL.
Please tell me how can I convert the row data (content of file) to a file and provide the link for the users inside the view.
You should follow the below steps:
I have store pdf file into storage/app/pdf
In controller:
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request, $file)
{
$file = storage_path('app/pdf/') . $file . '.pdf';
if (file_exists($file)) {
$headers = [
'Content-Type' => 'application/pdf'
];
return response()->file($file, $headers);
} else {
abort(404, 'File not found!');
}
}
if laravel below 5.2:
Add use Response; above controller class in the controller.
public function index(Request $request, $file)
{
$file = storage_path('app/pdf/') . $file . '.pdf';
return Response::make(file_get_contents($file), 200, [ 'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$file.'"'
]);
}
In web.php
Route::get('/preview-pdf/{file}', 'Yourcontroller#index');
In the blade view:
PDf
According to the Laravel documentation you can simply use the download method on the Storage facade.
From your controller, return the result of the command.
return Storage::disk('private')->download($file);

How to call API from controller Laravel without using curl and guzzle as its not working [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
How to call an API from a controller using a helper in laravel without using curl and guzzle because both returing nothing. I have tested in postman the api is working fine but not in laravel.
I need to call several API's from different controllers so what would be a good way to do this? Should i build a helper?
I used curl but it is always giving me a false response.
EDIT:
I am looking for a reliable way to make api calls to various url's without having to rewrite the sending and receiving code for each api I want to use.
Preferably a solution that implements "dry" (don't repeat yourself) principles and would serve as a base for any api specific logic, (parsing the response /translating for a model). That stuff would extend this base.
Update For Laravel 7.x and 8.x. Now we can use inbuilt Http(Guzzle HTTP) client.
docs:: https://laravel.com/docs/8.x/http-client#making-requests
use Illuminate\Support\Facades\Http;
$response = Http::get('https://jsonplaceholder.typicode.com/posts');
$response = Http::post('https://jsonplaceholder.typicode.com/posts', [
'title' => 'foo',
'body' => 'bar',
'userId' => 1
]);
$response = Http::withHeaders([
'Authorization' => 'token'
])->post('http://example.com/users', [
'name' => 'Akash'
]);
$response->body() : string;
$response->json() : array|mixed;
$response->object() : object;
$response->collect() : Illuminate\Support\Collection;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->failed() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;
For Laravel < 7 you need to install Guzzle pacakge
docs: https://docs.guzzlephp.org/en/stable/index.html
Installation
composer require guzzlehttp/guzzle
GET
$client = new \GuzzleHttp\Client();
$response = $client->get('https://jsonplaceholder.typicode.com/posts');
return $response;
POST
$client = new \GuzzleHttp\Client();
$body = [
'title' => 'foo',
'body' => 'bar',
'userId' => 1
];
$response = $client->post('https://jsonplaceholder.typicode.com/posts', ['form_params' => $body]);
return $response;
Some Usefull Methods
$response->getStatusCode();
$response->getHeaderLine('content-type');
$response->getBody();
we can also add headers
$header = ['Authorization' => 'token'];
$client = new \GuzzleHttp\Client();
$response = $client->get('example.com', ['headers' => $header]);
Helper For this Method
we can create a common helper for these methods.
Create a Helpers folder in app folder
app\Helpers
then create a file Http.php inside Helpers folder
app\Helpers\Http.php
add this code in Http.php
<?php
namespace App\Helpers;
use GuzzleHttp;
class Http
{
public static function get($url)
{
$client = new GuzzleHttp\Client();
$response = $client->get($url);
return $response;
}
public static function post($url,$body) {
$client = new GuzzleHttp\Client();
$response = $client->post($url, ['form_params' => $body]);
return $response;
}
}
Now in controller you can use this helper.
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
use App\Helpers\Http;
class Controller extends BaseController
{
/* ------------------------ Using Custom Http Helper ------------------------ */
public function getPosts()
{
$data = Http::get('https://jsonplaceholder.typicode.com/posts');
$posts = json_decode($data->getBody()->getContents());
dd($posts);
}
public function addPost()
{
$data = Http::post('https://jsonplaceholder.typicode.com/posts', [
'title' => 'foo',
'body' => 'bar',
'userId' => 1
]);
$post = json_decode($data->getBody()->getContents());
dd($post);
}
}
Without Helper
In Main controller we can create these functions
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
public function get($url)
{
$client = new GuzzleHttp\Client();
$response = $client->get($url);
return $response;
}
public function post($url,$body) {
$client = new GuzzleHttp\Client();
$response = $client->post($url, ['form_params' => $body]);
return $response;
}
}
Now in controllers we can call
<?php
namespace App\Http\Controllers;
class PostController extends Controller
{
public function getPosts()
{
$data = $this->get('https://jsonplaceholder.typicode.com/posts');
$posts = json_decode($data->getBody()->getContents());
dd($posts);
}
public function addPost()
{
$data = $this->post('https://jsonplaceholder.typicode.com/posts', [
'title' => 'foo',
'body' => 'bar',
'userId' => 1
]);
$post = json_decode($data->getBody()->getContents());
dd($post);
}
}

Provide link of a page in laravel

I have a database of questions which are viewed in localhost:8000/questions/{id}. I have created a chatbot in the existing laravel project. Now, I want to provide the user with the link of the question.
For example, if I want the link to a question of id=55, then the bot has to reply me with the link localhost:8000/questions/55.
How do I do that?
web.php
Route::resources([ 'questions' => 'QuestionController', ]);
Route::match(['get', 'post'], '/botman', 'BotManController#handle');
QuestionController.php
public function show(Question $question) {
return view('question')->with('question', $question);
}
botman.php
use BotMan\BotMan\BotMan;
use BotMan\BotMan\BotManFactory;
use BotMan\BotMan\Cache\DoctrineCache;
use BotMan\BotMan\Drivers\DriverManager;
use App\Conversations\StartConversation;
DriverManager::loadDriver(\BotMan\Drivers\Web\WebDriver::class);
$cachedriver = new Doctrine\Common\Cache\PhpFileCache('cache');
BotManFactory::create(config('botman', new
DoctrineCache($cachedriver)));
$botman = app('botman');
$botman->hears('Hello|Hi',
function($bot) {
$bot->typesAndWaits(1);
$bot->startConversation(new StartConversation);
}
);
BotManController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use BotMan\BotMan\BotMan;
use BotMan\BotMan\BotManFactory;
use BotMan\BotMan\Messages\Conversations;
use App\Conversations\StartConversation;
class BotManController extends Controller {
public function handle() {
$botman = app('botman');
$botman->listen();
}
public function startConversation(Botman $bot) {
$bot->startConversation(new StartConversation());
}
}
first we get all the ids from the questions table:
$questions = DB::table('questions')->select('id')->where('body', 'like', '%' . $answer . '%')->get();
$ids here is a collection of id so for each id we must create a link:
$links = array();
foreach($questions as $question){
$links[] = route('questions.show', ['id' => $question->id]);
}
so now we have all links needed to return as answer, finish it using $this->say... as you wish
you may want to return the first link not all links then get the first id from the database and create link using it:
$question = DB::table('questions')->select('id')->where('body', 'like', '%' . $answer . '%')->first()
$link = route('questions.show', ['id' => $question->id]);
then return the answer using $this->say
I hope this helps

why method post not found in Illuminate\support\facade\input

I work with laravael 5.3.9 .
In my controller I use
Illuminate\Support\Facades\Input;
But when I try to get input from a user form using method post like that :
function add(){
$fullName = Input::post('fullName' , 'test');
I get this error .
the only method that Input class has is "get" .
I dont want that in my system I want to work with method post , delete , put ....
I guess, Input::post method is not used with L5.3. Use the Request facade OR $request to get your input variable.
Try this in your controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class area_owners extends Controller
{
function add(Request $request)
{
// I assume all these input variable have same name in you FORM.
$fullName = $request->input('fullName');
$smsCode = $request->input('smsCode');
$authorizationId = $request->input('authorizationId');
$areaNumber‌​ = $request->input('areaNumber‌​');
$neigh_project_Id = $request->input('neigh_project_Id');
$area_owners = DB::table('area_owners')
->insert(['fullName'=>$fullName,
'smsCode'=>$smsCode,
'authorizationId'=>$authorizationId,
'are‌​aNumer'=>$areaNumber‌​,
'neigh_project_Id'=‌​>$neigh_project_Id])‌​;
return view('area_owners_add', ['area_owners' => $area_owners]);
}
}
Let me know if it helps.

Resources