update profile in laravel API for mobile apps - laravel

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

Related

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

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.

Intervention\Image\Exception\NotSupportedException Encoding format (tmp) is not supported

I am using the Intervention package with Laravel 5.6, the issue I am getting whenever I am uploading a file I have been presented with the error Encoding format(tmp) is not supported. I have my gdd2 extension enabled also. This is the code where I have used.
public function store(Request $request)
{
$this->validate($request , [
'name' => 'required|unique:categories',
'description' => 'max:355',
'image' => 'required|image|mimes:jpeg,bmp,png,jpg'
]);
// Get Form Image
$image = $request->file('image');
$slug = str_slug($request->name);
if (isset($image))
{
$currentDate = Carbon::now()->toDateString();
$imageName = $slug.'-'.$currentDate.'-'.uniqid().'.'.$image->getClientOriginalExtension();
// Check if Category Dir exists
if (!Storage::disk('public')->exists('category'))
{
Storage::disk('public')->makeDirectory('category');
}
// Resize image for category and upload
$categoryImage = Image::make($image)->resize(1600,479)->save();
Storage::disk('public')->put('category/'.$imageName, $categoryImage);
// Check if Category Slider Dir exists
if (!Storage::disk('public')->exists('category/slider'))
{
Storage::disk('public')->makeDirectory('category/slider');
}
// Resize image for category slider and upload
$categorySlider = Image::make($image)->resize(500,333)->save();
Storage::disk('public')->put('category/slider/'.$imageName, $categorySlider);
}
else
{
$imageName = 'default.png';
}
$category = new Category();
$category->name = $request->name;
$category->slug = $slug;
$category->description = $request->description;
$category->image = $imageName;
$category->save();
Toastr::success('Category Saved Successfully','Success');
return redirect()->route('admin.category.index');
}
You don't need to use the save() function on the Intervention\Image class as you are saving the file to your public disc via the Storage Facade.
Simply replace the line
$categoryImage = Image::make($image)->resize(1600,479)->save();
with
$categoryImage = Image::make($image)->resize(1600,479)->stream();
to avoid having to store the image to the temp folder under a .tmp extension. Laravel Storage Facade will handle the stream created by Intervention\Image and store the file to the public disk.
The Intervention image save() method requires a filename so it knows what file format (jpg, png, etc..) to save your image in.
The reason you are getting the error is it does not know what encoding to save the temporary image object (tmp) in.
Here is an example
->save('my-image.jpg', 90)
There is also a optional second parameter that controls the quality output. The above outputs at 90% quality.
http://image.intervention.io/api/save
Saw this somewhere and it worked for me
$image->save('foo' . $img->getClientOriginalExtension());
The Laravel Intervention image save() method requires a filename so it knows what file format (jpg, png, etc..) to save your image in
$categoryImage = Image::make($image)->resize(1600,479)->save( $imageName,90);
I've solved this by
Trimming
my file path, i was using this script inside laravel Artisan Console.
$img->save(trim('public/uploads/images/thumbnails/'.$subFolder.'/'.$filename));
Rather you use stream its working without error
$categoryImage = Image::make($image)->resize(1600,479)->save();
$categoryImage = Image::make($image)->resize(1600,479)->save();
Storage::disk('public')->put('category/'.$imageName, $categoryImage);
change to
Image::make($image)->resize(1600, 479)->save(storage_path('app/public/category').'/'.$imagename);
$categorySlider = Image::make($image)->resize(500,333)->save();
Storage::disk('public')->put('category/slider/'.$imageName, $categorySlider);
change to
Image::make($image)->resize(500, 333)->save(storage_path('app/public/category/slider/') .$imagename);

Laravel Upload Image and Generate Random ID as name

Whats the best way to generate and random ID number for every image where i want upload in Laravel 5?
My Upload:
<input type="file" id="mypicture" name="mypicture">
Controller:
public function MyPicture(Request $request){
$user = Auth::user();
$user->mypicture= $request->mypicture;
$user->save();
return redirect()->back();
}
Thats the way i do it always for other things:
->uniqueid = 'VA'.str_random(28);
how can i add it to my Controller for image name?
And how can i use only alphabetic character not numbers? Or i must change my DB Table.
Thanks
Try this:
public function MyPicture(Request $request){
$user = Auth::user();
$user->mypicture = date('mdYHis') . uniqid() . $request->mypicture;
$user->save();
return redirect()->back();
}
You can use Date (Y-m-d H:i:s) and uniqid() to generate unique name every file.
use uniqid()
if (Input::hasFile('mypicture')) {
$mypicture = Input::file('mypicture');
$user->mypicture= uniqid().$mypicture->getClientOriginalName();
}
Do the same here:
$user = Auth::user();
$user->mypicture = $request->mypicture;
$user->filename = str_random(28);
$user->save();
$request->mypicture->storeAs('images', $user->filename);
If you want to use only letters, use one of the existing solutions.
Laravel has an inbuilt method for this, using their File facade.
From laravel docs:
$path = $request->file('avatar')->store('avatars');
return $path;
By default, the store method will generate a unique ID to serve as the file name. The path to the file will be returned by the store method so you can store the path, including the generated file name, in your database.

Attach authenticated user to create

I'm trying to attach the currently logged in user to this request, so that I can save it in the database. Can someone point me in the right direction, please?
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$leadStatus = $this->leadStatusRepository->create($input);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}
So, I have come up with the following using array_merge, but there must be a better way, surely?
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$userDetails = array('created_by' => Auth::user()->id, 'modified_by' => Auth::user()->id);
$merged_array = array_merge($input, $userDetails);
$leadStatus = $this->leadStatusRepository->create($merged_array);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}
So you can use Auth Facade to get information of currently logged user.
For Laravel 5 - 5.1
\Auth::user() \\It will give you nice json of current authenticated user
For Laravel 5.2 to latest
\Auth::guard('guard_name')->user() \\Result is same
In laravel 5.2, there is new feature called Multi-Authentication which can help you to use multiple tables for multiple authentication out of the box that is why the guard('guard_name') function is use to get authenticated user.
This is the best approach to handle these type of scenario instead of attaching or joining.
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$userDetails = \Auth::user(); //Or \Auth::guard('guard_name')->user()
$leadStatus = $this->leadStatusRepository->create($input);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}
Hope this helps.

creating a folder once user registred laravel 5

I would like to create a folder inside Storage folder in Laravel 5, once you register and pick your username, a folder with that user will be created for you.
If you created user : john5500 a folder inside Storage will be created with 'john5500' and will belong only to that user.
Mark, see the code below.
This code I use to create a new user in my database.
Information about ManagementCreateRequest $Request can be found via this URL.
Laravel Controller Validation
In short I'm validating my input via Controller Validation in Laravel.
After the validation passes I get all the data from the validation in the variable $Request.
After that I create the user as below. After creating the user I send a redirect to the management page. This page contains an overview of all the users in the database.
public function store(ManagementCreateRequest $Request)
{
// Create user
Management::create($Request->all());
// Return view
return redirect('management')
->with('Success', 'User created.');
}
If I would to create a directory I would do it like this.
public function store(ManagementCreateRequest $Request)
{
// Create user
Management::create($Request->all());
// Create directory
File::MakeDirectory('/path/to/directory' . $Request->username);
// Return view
return redirect('management')
->with('Success', 'User created.');
}
Replace /path/to/directory with the actual path to your storage directory.
For example: Under CentOS my storage directory would be.
/var/www/Site Name/storage
Don't forget to replace 'Site Name' with the name of your Laravel site.
More detailed information about File:makeDirectory can be found via this link:
Laravel Creating Directory
Lravel 5 comes with an excellent filesystem. You could simply do:
Storage::makeDirectory($directory);
See the documentation for more details: http://laravel.com/docs/5.0/filesystem#basic-usage
You can use Laravel File Facade:
File::makeDirectory($path, $mode = 0755, $recursive = false, $force = false);
Ensure storage is writable
public function create(array $data)
{
//return
$user = User::create([
'name' => $data['name'],
'username'=>$data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
\File::makeDirectory(storage_path($data['username']));
return $user;
}

Resources