I want to save my images with using save_image() function in media model..
Here is my media model;
class Media extends Model
{
public function save_image($file)
{
$realname = str_slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
$extension = $file->getClientOriginalExtension();
$new_name = str_slug($realname) . "-" . time() . "." . $extension;
$file->move(public_path('uploads'), $new_name);
$image = DB::create([
'image' => $new_name,
'image_path' => "uploads/" . $new_name,
'image_alt_name' => $realname
]);
return $image;
}
}
in my controller;
public function storeMedia(Request $request)
{
$this->validate($request,[
'image'=> 'required|mimes:jps,png,gif,jpeg'
]);
$image=$request->file('image');
$media = new Media();
$media->save_image($image);
return response()->json([
'url'=> env('APP_URL')."/".$image->image_path,
'alt' => $image->image_alt_name,
'id' => $image->id,
]);
}
Are we have to say DB::table('media') at the first ? I mean, we are already on media model, is that necesary ?
You are not specifying the table name in your code.
Here is the Solution
$image = DB::table('media')->create([
'image' => $new_name,
'image_path' => "uploads/" . $new_name,
'image_alt_name' => $realname
]);
OR
$image = Media::create([
'image' => $new_name,
'image_path' => "uploads/" . $new_name,
'image_alt_name' => $realname
]);
You can also use $this->create
Hope this helps
Query builder doesn't have create() method, so you need to use Eloquent:
Model::create([
'image' => $new_name,
'image_path' => "uploads/" . $new_name,
'image_alt_name' => $realname
]);
If you want to use query builder, you can use the insert() method:
DB::table('table_name')->insert([
'image' => $new_name,
'image_path' => "uploads/" . $new_name,
'image_alt_name' => $realname
]);
Related
PLease help me on how to upload image in the folder and the same time in the database with a random name.
There's an error: Call to a member function getName() on null.
Heres my code in controller
`public function actionInsert()
{
$destination = new DestinationModel();
$name=$this->request->getVar('name');
$place=$this->request->getVar('place');
$location=$this->request->getVar('location');
$category=$this->request->getVar('category');
$description=$this->request->getVar('description');
$latitude=$this->request->getVar('latitude');
$longitude=$this->request->getVar('longitude');
$image=$this->request->getFile('image');
$imageName = $image->getName();
$image->move('im/destination', $imageName);
if($place == 'Calapan City')
{
$place = 'Calapan';
}else if($category == 'Destination')
{
$category ='Destination';
}
$data = [
'name' => $name,
'place' => $place,
'location' => $location,
'category' => $category,
'image' => $place. '/'. $imageName,
'description' => $description,
'latitude' => $latitude,
'longitude' => $longitude
];
$destination->save($data);
return view('adding_place');
}`
I am having 2 methods. In one of the method I am making a call to database, a pure and simple one Document::findOrFail($data->id). But this is always returning me null although a record is already persisted. Any idea how to get this simple thing sorted?
public function lockExport(Request $request){
$document = Document::create([
'user_id' => $this->userId(),
'extension' => $extension,
'name' => $filename,
'file_path' => $filepath,
'size' => File::size($filepath . $filename),
'received_at' => Carbon::now()->format('Y-m-d')
]);
$isAttachment = false;
Cache::put($token, ['file' => $document->file_path . $document->name . '.' . $document->extension, 'is_attachment' => $isAttachment, 'id' => $document->id], 3);
return $this->downloadlockExport($token);
}
public function downloadlockExport($token)
{
try {
$data = (object) Cache::get($token);
// dd I get the full $data as object
$document = Document::findOrFail($data->id);
// undefined. Above query did not execute.
// Thus, below query failed
$document->update(['downloads' => $document->downloads + 1]);
$content = Crypt::decrypt(File::get($data->file));
return response()->make($content, 200, array(
'Content-Disposition' => 'attachment; filename="' . basename($data->file) . '"'
));
} catch (\Exception $e) {
\App::abort(404);
}
}
What you probably would like to do is:
public function lockExport(Request $request){
$document = Document::create([
'user_id' => $this->userId(),
'extension' => $extension,
'name' => $filename,
'file_path' => $filepath,
'size' => File::size($filepath . $filename),
'received_at' => Carbon::now()->format('Y-m-d')
]);
$isAttachment = false;
$token = 'mytoken';
Cache::put($token, ['file' => $document->file_path . $document->name . '.' . $document->extension, 'is_attachment' => $isAttachment, 'id' => $document->id], 3);
return $this->downloadlockExport($token);
}
This way you will get your $token in your called function and you will get the $data correctly as I see.
And in the downloadlockExport() function you will have the ID like this:
$document = Document::findOrFail($data->mytoken['id']);
or you can use:
$document = Document::findOrFail($data->$token['id']);
similar with getting the File value:
$content = Crypt::decrypt(File::get($data->$token['file']));
I'm new to laravel. I get the following error when uploading a file:
Call to a member function move() on null
$file = $request->file('img');
$destinationPath = base_path('\public\img');
$file->move($destinationPath . $file->getClientOriginalName());
$dealer = new Dealer([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $request->get('img'),
]);
Why dont You Try it like this ?
if ($request->hasFile('img')) {
$image = $request->file('img');
$teaser_image = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $img);
} else {
dd('Request Has No File');
}
and For Your Store :
$dialer = Dialer::create([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $request->get('img') ?? null,
]);
You Can remove ??null for making sure that you get The image And store it in database but You can Even place It To make it Optional for the User To insert img or not . hope this helps
EDIT
According to your comment i guess you may have 2 problems :
first one be sure that you have and input that named 'img' that sends the image and the secound is that be sure to add the multi enctype to your form so that form can send image like below :
enctype="multipart/form-data"
so your form should be like this :
<form action="someRoute" method="post" enctype="multipart/form-data">
if ($request->hasFile('img')) {
$image = $request->file('img');
// print_r($image);
$image_name = time().'.'.$image->getClientOriginalExtension();
// echo $image;
// exit(0);
$destinationPath = base_path('Uploads');
$image->move($destinationPath, $image_name);
$dealer = new Dealer([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $image_name,
]);
$dealer->save();
Session::flash('msg','Data Added successfully');
Session::flash('type','success');
return redirect('dealer-master');
// // echo $image;
// // exit(0);
// $destinationPath = base_path(' Uploads');
// $image->move($destinationPath, $image_name);
}
else {
Session::flash('msg','Please Check the data');
Session::flash('type','fail');
return redirect('dealer-master');
// echo $request;
}
I Findout my mistake This is working good Thank U Guys...!
It's work form me
if($request->img){
$fileName = time() . '.' . $request->img->extension();
$request->img->move(storage_path('app/public/img'), $fileName);
}
$dealer = new Dealer([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $fileName ?? null,
]);
$dealer->save();
I've got problem setting the avatar name so I can put to the database, it shows an object and not the filename, as you can see I've echo $filename to make sure I've got the name of the image. but when I print_r($sanitized), the image is an object.
My expected result of $sanitized should be:
Array
(
[email] => superadmin#email.com
[name] => Superadmin
[phone] => 123123
[avatar] => 1_avatar1546579727.jpg
)
Code:
public function updateProfile(Request $request)
{
$this->setUser($request);
$user = $this->user;
// Validate the request
$this->validate($request, [
'email' => ['sometimes', 'email', Rule::unique('users', 'email')->ignore($this->user->getKey(), $this->user->getKeyName()), 'string'],
'name' => ['nullable', 'string'],
'phone' => ['sometimes', 'string'],
'avatar' => ['sometimes', 'image', 'mimes:jpeg,png,jpg,gif', 'dimensions:min_width=500,min_height=500', 'max:2048'],
], [
'avatar.mimes' => 'Uploaded file format should be jpeg, jpg, png or gif.',
'avatar.dimensions' => 'Image should have minimum 200x200px dimensions.',
'avatar.max' => 'Maximum allowed file size is 2 MB.',
]);
if($request->hasFile('avatar')) {
$filename = $user->id.'_avatar'.time().'.'.request()->avatar->getClientOriginalExtension();
Image::make(request()->avatar)->resize(300, 300)->save( public_path('uploads/avatars/'.$filename) );
// $request->avatar = $filename;
$request['avatar'] = $filename;
}
// Sanitize input
$sanitized = $request->only([
'email',
'name',
'phone',
'avatar'
]);
echo $filename . "</br>";
echo "<pre>";
print_r( $sanitized );
echo "</pre>";
return "";
// $this->user->update($sanitized);
// return redirect()->back()->with('success', 'Profile has been updated.');
}
EDIT 1
I've tried all your answers, it still the same results.
Code:
if($request->hasFile('avatar')) {
$filename = $user->id.'_avatar'.time().'.'.request()->avatar->getClientOriginalExtension();
Image::make(request()->avatar)->resize(300, 300)->save( public_path('uploads/avatars/'.$filename) );
//This is what I've tried so far below:
$request->request->add(['avatar', $filename]);
// $request->merge(['avatar' => $filename]);
// $request->avatar = $filename;
// $request['avatar'] = $filename;
}
I've just fixed it by just giving me a hint of #Md.Sukel Ali
I've moved the $sanitzed = $request.. to the top, then update it and not using directly $request variable.
Working Code:
public function updateProfile(Request $request)
{
$this->setUser($request);
$user = $this->user;
// Validate the request
$this->validate($request, [
'email' => ['sometimes', 'email', Rule::unique('users', 'email')->ignore($this->user->getKey(), $this->user->getKeyName()), 'string'],
'name' => ['nullable', 'string'],
'phone' => ['sometimes', 'string'],
'avatar' => ['sometimes', 'image', 'mimes:jpeg,png,jpg,gif', 'dimensions:min_width=500,min_height=500', 'max:2048'],
], [
'avatar.mimes' => 'Uploaded file format should be jpeg, jpg, png or gif.',
'avatar.dimensions' => 'Image should have minimum 200x200px dimensions.',
'avatar.max' => 'Maximum allowed file size is 2 MB.',
]);
// Sanitize input
$sanitized = $request->only([
'email',
'name',
'phone',
'avatar'
]);
if($request->hasFile('avatar')) {
$filename = $user->id.'_avatar'.time().'.'.request()->avatar->getClientOriginalExtension();
Image::make(request()->avatar)->resize(300, 300)->save( public_path('uploads/avatars/'.$filename) );
$sanitized['avatar'] = $filename;
}
echo $filename . "</br>";
echo "<pre>";
print_r( $sanitized );
echo "</pre>";
return "";
// $this->user->update($sanitized);
// return redirect()->back()->with('success', 'Profile has been updated.');
}
What to here ?
how to assign the value of $filenameTosTor for my 'photo' which is a database column?
public function update(Request $request, User $user)
{
$filenameWithExt = $request->file('profile_pic')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
Get the Extention
$extention = $request->file('profile_pic')->getClientOriginalExtension();
$filenameToStore = $filename.'_'.time().'.'.$extention;
$path = $request->file('profile_pic')->storeAs('public/profile_image', $filenameToStore);
$userupdate = User::where('id', $user->id)->update
([
'name' => $request->input('name'),
$user->profile_pic =$filenameToStore;
'photo'=> $request->($filenameToStore);
'last_name' => $request->input('last_name'),
'phone_number' => $request->input('phone_number'),
'address' => $request->input('address'),
'facebook_link' => $request->input('facebook_link'),
'twittr_link' => $request->input('twittr_link'),
'youtube_link' => $request->input('youtube_link'),
'Biography' => $request->input('Biography'),
]);
$userupdate->save();
return redirect('user.index');
}
Just use this variable like this:
'photo' => $filenameToStore,