how to upload image in laravel bootstrap auth package - laravel

i am trying to upload an image as a profile picture in laravel bootstrap auth package.
in this i am trying to change some package files to upload image. also i added a column in users table.
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'campus_id' => $data['campus_id'],
'role' => $data['role'],
'remarks' => $data['remarks'],
'image' => $data['image'],
]);
}
i make changes in Auth controller in validation function
also makes some changes in user store function

I think you need to move user profile image before create its entry inside database.
protected function create(array $data)
{
$imageName = time().'.'.$data['image']->extension();
//$data['image']->move(public_path('images'), $imageName);
$data['image']->storeAs('public/images', $imageName);
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'campus_id' => $data['campus_id'],
'role' => $data['role'],
'remarks' => $data['remarks'],
'image' => $imageName,
]);
}

You can use Image intervention for this. After installing you can use it in your controller as use Image;
$image = $request->file('image');
$img_name = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize( 847.5, 431 )->save('uploads/sliders/'.$img_name);
$image_path = 'uploads/sliders/'.$img_name;
Slider::create([
'title' => $request->title,
'image' => $image_path,
'created_at' => Carbon::now()
]);
1st you need to move your image to your desired directory inside public folder and save that directory in the database.

Related

Can't store image upload on public folder laravel

I'm trying to create an register form that includes an image upload. When I submit the form, it stores an "/private/var/tmp/" path for the image on database and the image is not stored anywhere in the public folder. I don't know what I might be doing wrong. Please help.
My config/filesystems:
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
My controller CreateNewUser:
class CreateNewUser implements CreatesNewUsers
{
use PasswordValidationRules;
protected function validator(array $input)
{
return Validator::make( $input, [
'firstname' => ['required', 'string', 'max:255'],
'lastname' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'email',
'max:255',
Rule::unique(User::class),
],
'mobile' => ['required', 'int'],
'country' => ['required', 'string', 'max:255'],
'password' => $this->passwordRules(),
'db_upload' => ['required', 'image'] //This the image I want to upload
]);
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
$imageUrl = $this->storeImage($request);
$input = $request->all();
$input['db_upload'] = $imageUrl;
$user = $this->create($input);
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
protected function storeImage(Request $request) {
$path = $request->file('db_upload')->store('public/uploads');
return substr($path, strlen('public/'));
}
public function create(array $input)
{
$user = User::create([
'firstname' => $input['firstname'],
'lastname' => $input['lastname'],
'email' => $input['email'],
'mobile' => $input['mobile'],
'country' => $input['email'],
'password' => Hash::make($input['password']),
'db_upload' => $input['db_upload'],
]);
$user->notify(new WelcomeEmailNotification());
return $user;
}
}
Try changing your storeImage function as below
protected function storeImage(Request $request) {
return $request->file('db_upload')->store('uploads', 'public');
}
Also ensure that you have created the symlink to the public disk by running php artisan storage:link and that after running the command there is a symlink visible in the <app-root>/public folder
Change the line of code that saves the file from:
$path = $request->file('db_upload')->store('public/uploads');
to
$path = $request->file('db_upload')->store('uploads', 'public');
The first argument is the path and the second argument is the disk you want to save to.
You can use the storePublicly() function to store the file in the public folder:
$file = $request->file('db_upload');
$path = $file
->storePublicly('files', ['disk' => 'public']);

User create and update using updateOrCreate()

I am creating and updating user using below code.
public function store(Request $request)
{
if ($request->ajax()) {
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users,email,' .$request->user_id,
'password' => 'required',
'role' => 'required',
]);
$user = User::updateOrCreate(['id' => $request->user_id],
[
'name' => $request->name,
'email' => $request->email,
'role' => $request->role,
'password' => Hash::make($request->password)
]);
}
}
When I am updating record Password is updating also. How can I solve the issue ?
How validation is working here 'email' => 'required|email|unique:users,email,' .$request->user_id, when I am creating a record ? Because when I am creating a record at that time $request->user_id is not available.

How to access the reset password mailable in the new version of laravel

I would like to use the reset password mailable for my project but I do not know how to access it in laravel 6.1
Here is my method
public function store(Request $request)
{
$validatedData = $request->validate([
'address_id' => 'required',
'name'=> 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'POBox' =>['required', 'min:6', 'max:6'],
'role_id' => 'required',
]);
$quickpass = substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 10 );
$newuser = User::create([
'address_id' =>$request->address_id,
'name'=> $request->name,
'email' => $request->email,
'POBox'=> $request->POBox,
'password' => Hash::make($quickpass),
'role_id' => $request->role_id,
]);
Mail::to($newuser->email)
->send( );
return view('admin.index')->with('message','The user has been created and a password reset email has been sent to them.');
}
The Notification used is Illuminate\Auth\Notifications\ResetPassword. It builds a MailMessage inline.
The PasswordBroker can be used to create the token and send off the notification for you. The method sendResetLink will take an array of credentials to find the User by.
Illuminate\Auth\Passwords\PasswordBroker
$resp = Illuminate\Support\Facades\Password::broker()->sendResetLink([
'email' => '...',
]);

Laravel Spatie Medialibrary: upload multiple images through REST API

I'm using the Spatie MediaLibrary library in a Laravel application. I want to upload 0 or more photos to my app via a REST API.
I can get it to work when the photo attribute contains 1 file
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'slug' => 'required',
'description' => 'required',
'price' => 'required|integer',
'photo' => 'nullable|file'
]);
$listing = Listing::Create([
'user_id' => auth('api')->user()->id,
'name' => $request->name,
'slug' => $request->slug,
'description' => $request->description,
'price' => $request->price,
]);
// stores the photo
if ($request->hasFile('photo')) {
$listing->addMediaFromRequest('photo')->toMediaCollection('photos');
}
return new ListingResource($listing);
}
The postman request looks as follows:
I know want to change the code so it can handle multiple photos in the request. I'm using the following code in the controller above to do so:
if ($request->hasFile('photo')) {
foreach ($request->input('photo', []) as $photo) {
$listing->addMediaFromRequest('photo')->toMediaCollection('photos');
}
}
and I have changed the attribute to photos[] instead of photo.
The code never goes into the foreach loop even.
Anyone has a hint on how to solve this?
Apparently the Spatie Medialibrary has a function called addMultipleMediaFromRequest. The full code is now
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'slug' => 'required',
'description' => 'required',
'price' => 'required|integer',
'photo' => 'nullable'
]);
$listing = Listing::Create([
'user_id' => auth('api')->user()->id,
'name' => $request->name,
'slug' => $request->slug,
'description' => $request->description,
'price' => $request->price,
]);
if ($request->hasFile('photo')) {
$fileAdders = $listing->addMultipleMediaFromRequest(['photo'])
->each(function ($fileAdder) {
$fileAdder->toMediaCollection('photos');
});
}
return new ListingResource($listing);
}
In Postman, I'm calling it as follows:
documentation reference
I managed to upload multiple files like this:
if($request->file('photos')) {
foreach ($request->file('photos') as $photo) {
$post->addMedia($photo)->toMediaCollection('post');
}
}
Check this out:
https://github.com/spatie/laravel-medialibrary/issues/227#issuecomment-220794240
This code is working for me.
View
<input type="file" name="photo[]" multiple />
ListingController
public function store(Request $request)
{
if ($request->hasFile('photo')) {
$fileAdders = $listing->addMultipleMediaFromRequest(['photo'])
->each(function ($fileAdder) {
$fileAdder->toMediaCollection('photos');
});
}
}

I have added avatar column to the generated users table, how to make default value to the avatar column

I am using Laravel Framework, I have generated all Register and Login through "$php artisan make:auth" command, now I have added a new column called "avatar" in the users table, and I want to set it to "noimage.jpg", so each time I register by default "noimage.jpg" will be added.
RegisterController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'avatar' => 'noimage.jpg' //How it suppose to be?
]);
}
You also have to add avatar to the $fillable property of your model. Otherwise you cannot assign it with create. See docs on Mass Assignment.
Instead you could manually assign the avatar:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user->avatar = 'noimage.jpg';
return $user;
}
Another way to set a default value for your model is to use Laravel lifecycle:
const DEFAULT_AVATAR = 'noimage.jpg'
protected static function boot()
{
parent::boot();
static::creating(function (User $user) {
if (!$user->avatar) {
$user->avatar = self::DEFAULT_AVATAR;
}
});
}
See: https://laravel.com/docs/5.8/eloquent#events

Resources