Laravel GET image as file along with other data - php

I have an Ionic application that communicates with my Laravel api. I'm trying to get the product details and image from the api and display that data in my Ionic app. I have the images stored on the local disk and also have a db table that contains the path name for each image. But when the Ionic app gets this data back, it just gets a json object that contains the mainImage with a path to the local disk, which of course, I can't use as an img src. My question is, how do I pass the mainImage as a file rather than a json object?
Here is my Laravel function:
public function api_get_non_disliked_for_user($categoryId)
{
$allProducts = Product::with('mainImage')
->where('subSubCategoryId', "=", $categoryId)->orderBy('title')->get();
return $allProducts;
}
In Product Model:
public function mainImage(){
return $this->hasOne('App\MainImage', 'productId');
}
In MainImage Model:
public function product(){
return $this->belongsTo('App\Product', 'productId');
}

The API should provide the url to the image, not the image file, specially when using Ionic as the front end, because then you just use the url in your html markup and the image will get downloaded automatically.

Related

How to call other function from the same controller in Laravel application?

I'm very new to Laravel and I was given a Laravel project, where I need to add some new features. The person, who has previously worked on that project hadn't left even a single comment in the code and now I must make my own scenarios about the features.
I have a controller, defined with some functions (dashboard, show_project, save_project etc.) and in one of my function, I need to use the result of calling other function.
In the concrete example, the call is made from "http://127.0.0.1:8000/username/project_slug" - there is a button "Save" and post function, called on onClick event. The function, whose output I need is normally called on "http://127.0.0.1:8000/username/project_slug/svg", which returns a view.
For better understanding, there's an example of the flow:
The user wants to save his/her project (an UML diagram) but in order to have a thumbnail, a function which generates a view (SVG format) will be called and the idea is, to take the HTML content of the page, which is on "http://127.0.0.1:8000/username/project_slug/svg" and to pass it to another API in order an image to be generated.
So far, I tried with cURL, file_get_contents, file_get_html, render methods but when I return the output, the server just keeps waiting and shows no error messages.
//The both functions are in ProjectController.php
/**
* A function, for saving the json file, where the whole of the diagram
* components are described. From the frontend we receive the project_id and
* the project_data(the json content).
*/
public function save_project(Request $request) {
$input = $request->only(['project_id', 'project_data']);
/*
Here we need to call the other function, to render the HTML content
and to pass it to the other API. Then we save the result with the
other information.
*/
/*
What I've tried?
$new_link = 'http://' . $_SERVER['HTTP_HOST'] . "/$username"
."/$project_slug" . "/svg";
$contents = file_get_contents($new_link);
return $contents;
*/
//In the same way with cURL.
$project = Project::where('user_id',session('userid'))
->where('id',$input['project_id'])->first();
$project->project_data = json_encode($input['project_data']);
if($project->save()) {
return ["status"=>"saved"];
}
else {
return ["status"=>"error"];
}
}
/**
* A function, which takes the the Json content (project_data) from the
* database and passes it to the view, where the Json is transformed in HTML
* tags.
*/
public function generate_svg(Request $request,$username,$project_slug) {
if(session('username')!=$username) {
return redirect("/");
}
$userid = session('userid');
$project = Project::where([
'user_id' => $userid,
'slug' => $project_slug,
])->first();
if(!is_null($project)) {
return view('svg',compact('project'));
}
}
I've read about some possible ways, including Guzzle request but maybe I haven't understood correctly the idea:
If I need to make a Guzzle request from my controller to the other function inside my controller, do I need an API configuration?
What I mean? Example:
Before saving the project, the user is on this URL address "http://127.0.0.1:8000/hristo/16test". Inside the controller, I have in session variables the token, the username(hristo) and i can get the project_name(16test) from the URL but after passing this URL to the generate_svg function, there is no indication of error or success.
So I'm missing some kind of token information?
If you just need the response of the other function you can just use
$response = $this->generate_svg($request, $username, $project_slug);
If you'll need to use this function from a different controller you can use this
app('App\Http\Controllers\UsernameController')->generate_svg($request, $username, $project_slug);

Laravel send data via request to another project

I have a laravel api controller where I'm getting data from a table.
public function moveData() {
$movelivesales = DB::table('st_sales_live')->get();
return $movelivesales;
}
I'm getting all the data, now how can I send this data to another project api(this api is ready) using request ? Any help please?
Just create a route like this to get your data($movelivesales):
Route::get('/your/path', 'YourController#moveData');
Then if you access:
http://yourdomain.com/your/path you will get a json of your data
You can get the data from api with php: file_get_contents('http://yourdomain.com/your/path');

How to get file array in Symfony controller?

I've user Symfony for the my application service. One service call send file array (multiple files) in post. how can i get that?
because when I use below code and dump $uploadedFiles is empty. when send single image, it work, any help?
public function createAction(Request $request) {
$uploadedFiles = $request->files;
}
this not about multiple file upload as Multiple file upload with Symfony2 question. This is about how to get multiple files (file array) in Request

Laravel Dropzonejs file validation in hasmany table

I have a laravel app that uploads files. I need to check in the related table if the file exist. My user model hasmany(assets) The file info lives in the assets table. I am trying to pull the name out of the table and verify it against the file being uploaded in dropzone.
Here is my dropzone script:
Dropzone.options.dropzoneUpload = {
paramName: "asset", // The name that will be used to transfer the file
maxFilesize: 2, // MB
accept: function(file, done) {
if (file.name == "{{$filename}}") {
done("Naha, you don't.");
}
else { done(); }
}
};
My function that generates my view for my upload page looks like this
public function index()
{
$filename = Auth::user()->assets->name;
return view('upload.index')->with('filename', $filename);
}
I get an error returned on the name in the filename variable
Undefined property: Illuminate\Database\Eloquent\Collection::$name
I have no idea how to access the file name from the table and verify it with the script in the view. Each user has multiple file names in the table.
Pre dropzone i was able to use this in my controller
foreach($userAssets as $asset)
{
if($asset->name == $filename)
{
return redirect('upload')->with('errornotice', 'A file with that name already exist');
}
}
but that won't work in the script.
Since you said yourself that your User hasMany Assets, what exactly is assets->name supposed to print? The name of which Asset? Since you have many of those and user->asset is returning a Collection, you could probably iterate that collection, construct a JSON array out of all Asset names and inject it into your JS. Then do a JavaScript for/each to check against all elements of the array. That's weak validation though, any user could edit the JS before submitting. If it's important to you that the filenames do not exist already, consider some kind of server-side validation.

url mapping in code igniter

I'm writing a PHP application using codeigniter framework. I'm trying to add a tool to download the data in the page as a .csv format file. I have the code to the server side, but I'm having trouble handling the URL mapping for the "Download" Controller.
in /controllers/ I have a controller called "Download", which is has a function called 'exportCSV', which receives a json object that is decoded and used to create the file. So, I'm trying to send a JavaScript array through 'post' to that method, but I'm having trouble handling the URL mapping.
here is my javascript call ...
function download(){
$.post('index.php/download/exportCSV', {input : dataForDownload.toString()},
function(answer){
alert(answer);
}
);
}
POST to index.php/download/exportcsv. CI doesn't much like Mixed Case controllers.
If you have a download controller, it should look like this:
class Download extends CI_Controller
{
function _construct()
{
parent::_construct();
}
function exportcsv()
{
if($this->input->post())
{
// Something was POSTed, continue
// process input
} else {
// Catch error if no POST
}
}
}
If you're getting a 404, your application might not be set up correctly. Check routes.php and your base_url.
I also recommend the CodeIgniter user guide. It's full of good information:
http://codeigniter.com/user_guide/overview/appflow.html
http://codeigniter.com/user_guide/overview/mvc.html

Categories