我想在媒体模型中使用save_image()函数来保存我的图像。
这是我的媒体模型;
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;
}
}
在我的控制器中;
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,
]);
}
我们首先要说DB::table('media')
吗?我的意思是,我们已经在媒体模型,是必要的吗?
答案 0 :(得分:0)
您没有在代码中指定表名。
这是解决方案
$image = DB::table('media')->create([
'image' => $new_name,
'image_path' => "uploads/" . $new_name,
'image_alt_name' => $realname
]);
或强>
$image = Media::create([
'image' => $new_name,
'image_path' => "uploads/" . $new_name,
'image_alt_name' => $realname
]);
您也可以使用$this->create
希望这有帮助
答案 1 :(得分:0)
“查询”构建器没有create()
方法,因此您需要使用Eloquent:
Model::create([
'image' => $new_name,
'image_path' => "uploads/" . $new_name,
'image_alt_name' => $realname
]);
如果要使用查询构建器,可以使用insert()
方法:
DB::table('table_name')->insert([
'image' => $new_name,
'image_path' => "uploads/" . $new_name,
'image_alt_name' => $realname
]);