I'm new at laravel and i was reading the document for a week now. i was working on crud about modification of register form i'm almost finish but then i bump in to this problem which is now i'm trying to look for a right syntax on my question would be how to i check and move a file use as a parameter to store and create a path folder for the image. similar to the code below i show using Request. cause if you look at the register page controller at the create function the parameter used is array.
tried reading documents and research couldn't find any or maybe i lack of keywords to direct me into this type of problem.
I have this code and this is right
public function store(Request $Request)
{
$ProfileUser = new User();
if($Request->hasfile('Img1'))
{
$file = $Request->file('Img1');
$extension = $file->getClientOriginalExtension(); // Get Image Ext.
$filename = time() . "." . $extension;
$file->move('uploads/employee/', $filename);
$ProfileUser->image1 = $filename;
} else
{
return $Request;
$ProfileUser->image1 = 'no image';
}
$ProfileUser->fname = $Request->input('fname');
$ProfileUser->mname = $Request->input('mname');
$ProfileUser->lname = $Request->input('lname');
$ProfileUser->homeaddress = $Request->input('homeaddr');
$ProfileUser->mobilenum = $Request->input('mobilenum');
$ProfileUser->accounttype = $Request->input('typeAcc');
$ProfileUser->image1 = $Request->input('img1');
$ProfileUser->save();
return redirect()->route('home');
}
but then i also have this modification in make:auth i made and added columns
this is my problem here since the function is using an array instead of the Request.
protected function create(array $data) <-- this is the Error
{
if($data->hasFile('image1')) { <-- from here to:
$file = $data->file('image1');
$extension = $file->getClientOriginalExtension(); // Get Image Ext.
$filename = time() . "." . $extension;
$file->move('uploads/employee/', $filename);
} else {
return $request;
} <-- here this function
$user = User::create([
'name' => $data['fname'] . " " . $data['lname'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'fname' => $data['fname'],
'mname' => $data['mname'],
'lname' => $data['lname'],
'homeaddress' => $data['homeaddr'],
'mobilenum' => $data['mobilenum'],
'accounttype' => $data['typeAcc'],
'image1' => $data['image1']
]);
return $user;
}
if i commend out the file validation the create function work fine and is able to save to database but then i need the image to be move on the 1st function it works perfect but in the 2nd using a parameter array doesn't i know i have maybe a wrong syntax which i ask for now how. and if it's ok can you guys explain a bit about the difference between Request vs Array? that i may able also to understand both
The $Request variable contains an object from the Laravel Request class (Illuminate \ Http \ Request). Read more about here
An Array is a PHP data structure. Read about arrays in PHP here.
To get all request's data as an array, you can call the method all() on the request object. It will give you an associative array.
$request->all();
Related
I'm trying to build a REST API with Laravel where users need to update their images. In this case the image has been successfully saved in storage, but I want a response in the form of a link that can be accessed by the frontend later. However, the response was not found. Is there a solution to this problem? Here I attach my code
public function update(Request $request,$userId)
{
$user= User::find($userId->id);
// $photoWithExt= $request->file('photo')->getClientOriginalName();
$filename = $user['nip'];
$extension = $request->file('photo')->getClientOriginalExtension();
$fileNameToStore ='/images/users/'.$filename.'.'.$extension;
$path= $request->file('photo')->storeAs('',$fileNameToStore);
$user->update([
'username'=>$request['username'],
'name'=>$request['name'],
'photo'=> $path
]);
return $user;
}
This is response in postman
And when I click the link path, the image is 404. I hope someone can help with this problem
Assuming that you're using Local Drive, you have to get the absolute link to the file
(...)
$user->update([
'username'=>$request['username'],
'name'=>$request['name'],
'photo'=> Storage::disk('local')->get($path); // <---
]);
return $user;
}
I have found the answer,
public function update(Request $request,$userId)
{
$user= User::find($userId->id);
$filename = $user['nip'];
$extension = $request->file('photo')->getClientOriginalExtension();
$fileNameToStore ='images/users/'.$filename.'.'.$extension;
$path= $request->file('photo')->storeAs('',$fileNameToStore,'public');
$photoURL = Storage::url($path); //base_url
$user->update([
'username'=>$request['username'],
'name'=>$request['name'],
'photo'=> $photoURL,
]);
return $user;
}
I have created a plugin and after the other processes of the plugin are done i would like to redirect to a given url from a controller in the backend.
i have created a plugin that creates a documents from orders and that is working fine. however at the end of the process i would like to redirect to a url that can download or open the document that has been created. i know the url for doing so is structured like this (http://localhost:8000/backend/Order/openPdf?id=harshvalueforpdf). i am using shopware version 5.5.1 in docker on my local host.
public function redirectmyurlAction()
{
$harsh = "9ce6b9a9cd5d469386fbb5bd692f9644";
$search_word = $harsh;
error_log(print_r(array('Reached redirect action'), true)."\n", 3, Shopware()->DocPath() . '/test.log');
$this->redirect(
array(
'module'=> backend,
'controller' => 'Order',
'action' => 'openPdf?id='.$search_word,
)
);
}
i expect that when the process reached this action the user is redirected to the created url and then it should be able to download or show the pdf. But it logs the log i put before the redirect but does not redirect. nothing is logged in errors or console. When i put the same redirect on the frontend i get the CSRFTokenValidationException which is what i expect, but it shows the redirect works there so why not in the backend.
Update:
After the responses,i have copied the function and modified it as below but it logs everything there and still does nothing am i missing something?
public function openmyPdf($DocHarsh, $orderId)
{
error_log(print_r(array('Entered openmyPdf function',$DocHarsh,$orderId,$date), true)."\n", 3, Shopware()->DocPath() . '/error.log');
$filesystem = $this->container->get('shopware.filesystem.private');
$file = sprintf('documents/%s.pdf', basename($DocHarsh));
if ($filesystem->has($file) === false) {
error_log(print_r(array('Entered if statement, file doesnt exists ',$DocHarsh,$orderId,$date), true)."\n", 3, Shopware()->DocPath() . '/error.log');
$this->View()->assign([
'success' => false,
'data' => $this->Request()->getParams(),
'message' => 'File not exist',
]);
return;
}
// Disable Smarty rendering
$this->Front()->Plugins()->ViewRenderer()->setNoRender();
$this->Front()->Plugins()->Json()->setRenderer(false);
$orderModel = Shopware()->Models()->getRepository(Document::class)->findBy(['hash' =>$DocHarsh]);
$orderModel = Shopware()->Models()->toArray($orderModel);
$orderId = $orderModel[0]['documentId'];
$response = $this->Response();
$response->setHeader('Cache-Control', 'public');
$response->setHeader('Content-Description', 'File Transfer');
$response->setHeader('Content-disposition', 'attachment; filename=' . $orderId . '.pdf');
$response->setHeader('Content-Type', 'application/pdf');
$response->setHeader('Content-Transfer-Encoding', 'binary');
$response->setHeader('Content-Length', $filesystem->getSize($file));
$response->sendHeaders();
$response->sendResponse();
$upstream = $filesystem->readStream($file);
$downstream = fopen('php://output', 'wb');
while (!feof($upstream)) {
fwrite($downstream, fread($upstream, 4096));
}
error_log(print_r(array('leaving the pdf function',$DocHarsh,$orderId,$upstream,$downstream), true)."\n", 3, Shopware()->DocPath() . '/error.log');
}
Please have a look at backend-controller of the order module. It should be the same case. This function is used for opening/downloading a document from the backend:
https://github.com/shopware/shopware/blob/5.5/engine/Shopware/Controllers/Backend/Order.php#L1113
I think it might be confusing for backend users to be redirected (from the backend context) to a new blank page with a download.
According to my own evaluation. I think the issue you are having is because this is not an action but simply a function try making it an Action and run it through the browser like the original one.
Don't forget to whitelist it.
use the class use Shopware\Components\CSRFWhitelistAware;
then
something like this
/**
* {#inheritdoc}
*/
public function getWhitelistedCSRFActions()
{
return [
'youropenPdfActionnamewithoutthewordAction'
];
}
and also add the implements CSRFWhitelistAware to your class declaration.
I am developing an api endpoint to use with my laravel and vue app.
public function avatar(Request $request)
{
$user = User::find(Auth::id());
$validator = Validator::make($request->all(), [
'avatar' => 'required'
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()]);
} else {
$image = $request->get('avatar');
//base64_decode($file_data)
$path = Storage::putFile('avatars', base64_decode($image));
$user->avatar_url = $path;
if ($user->save()) {
//return redirect()->route('user_profile_settings');
}
}
}
This is the code that I have I tried going off what I found online to accomplish file uploads with an api and using php, but I am getting this error "Call to a member function hashName() on string". The goal of this is to upload the file to a s3 bucket using the putFile method.
I believe your problem lies here:
$image = $request->get('avatar');
$path = Storage::putFile('avatars', base64_decode($image));
Per the docs, you're going to want to use $request->file('avatar') to access the file.
Then, you can do store('avatars') to store it in your default storage location.
In short:
$path = $request->file('avatar')->store('avatars');
Im using Laravel 5.2 with Socialite. I am able to pull out the details of the user but the problem is that the avatar is not being displayed properly if I inject it on its src.
Socialite returns an object wherein I could use it as $facebookDetails->getAvatar() in which returns a value of like this https://graph.facebook.com/v2.6/123456789/picture?type=normal
If I echo this value in the image src, it would look like this.
<img src="https://graph.facebook.com/v2.6/123456789/picture?type=normal" />
It seems that this is not the actual URL of the image since when I enter this on the browser, it redirects me to the "actual" image and displays the image.
How could I display the image on the img tag to display the actual image?
Simply fetch the data using file_get_contents function and process the retrieved data.
In Controller
use File;
$fileContents = file_get_contents($user->getAvatar());
File::put(public_path() . '/uploads/profile/' . $user->getId() . ".jpg", $fileContents);
//To show picture
$picture = public_path('uploads/profile/' . $user->getId() . ".jpg");
i'm using following code:
/**
* In order to save the user's avatar
* REMEMBER TO ADD "use File; use Illuminate\Support\Carbon; use DB;" TO TOP!
* #param $avatar Socialite user's avatar ($user->getAvatar())
* #param $userId User's id database
*/
public function saveImageAvatar($avatar, $userId)
{
$fileContents = file_get_contents($avatar);
$path = public_path() . '/users/images/' . $userId . "_avatar.jpg";
File::put($path, $fileContents);
DB::table('Images')->insert(
['path' => $path,
'nome' => 'avatar',
'users_id' => $userId,
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s')]);
}
I'm building a small asset management system in Laravel 5.2
A user can upload images, video etc to the app and the asset meta data gets stored in the assets table. While that's happening, the asset is renamed to match the asset id (I'm storing the original filename too), I'm storing the mime type and uploading the file to S3.
Where I've come unstuck is storing the S3 url in database.
This is my method
public function store(AssetRequest $request)
{
// Initialise new asset and set the name
// from the form
$asset = new Asset(array(
'name' => $request->get('name')
));
$asset->user_id = Auth::user()->id;
// save the asset to the db
$asset->save();
// set the file var = form input
$file = $request->file('asset_path');
$extension = $file->getClientOriginalExtension();
// modify the asset name
$assetFile = $asset->id . '.' . $request->file('asset_path')->getClientOriginalExtension();
// push the new asset to s3
Storage::disk('s3')->put('uploads/' . $assetFile, file_get_contents($file));
$asset->mime = $file->getClientMimeType();
$s3Url = Storage::url($file);
$asset->s3_url = $s3Url;
$asset->original_filename = $file->getClientOriginalName();
$asset->filename = $assetFile;
$asset->file_extension = $extension;
// return ok
$asset->save();
return \Redirect::route('asset.create')->with('message', 'Asset added!');
}
The lines relating to my attempt at storing the S3 url
$s3Url = Storage::url($file);
$asset->s3_url = $s3Url;
Only seems to store a temporary path /storage//tmp/php8su2r0 rather than an actual S3 url. I'd like to avoid having to set the bucket manually, rather hoping I can use what is configured in config/filesystem.php
Any ideas?
you can get everything from the config using the config(key) function helper
so to get the s3 public url of file, do this:
function publicUrl($filename){
return "http://".config('filesystems.disks.s3.bucket').".s3-website.".config('filesystems.disks.s3.region').".amazonaws.com/".$filename;
}
or you can use the underlying S3Client:(taken from here)
$filesystem->getAdapter()->getClient()->getObjectUrl($bucket, $key);
What your are trying to achieve, I have been doing that in many projects.
All you need to do is create image_url column in database. And pass the s3 bucket link + the name of the file + the extension.
You should know the bit that is constant for me like : https://s3-eu-west-1.amazonaws.com/backnine8/fitness/events/ then I have the id and the extension. in your case it could be name and extension.
if(Input::get('file')) {
$extension = pathinfo(Input::get('filename'), PATHINFO_EXTENSION);
$file = file_get_contents(Input::get('file'));
$s3 = AWS::get('s3');
$s3->putObject(array(
'ACL' => 'public-read',
'Bucket' => 'backnine8',
'Key' => '/fitness/events/'.$event->id.'.'.$extension,
'Body' => $file,
));
$event->image_url = 'https://s3-eu-west-1.amazonaws.com/backnine8/fitness/events/'.$event->id.'.'.$extension;
$event->save();
}