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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments