【问题标题】:laravel update function is not workinglaravel 更新功能不起作用
【发布时间】:2014-06-26 23:05:41
【问题描述】:

我想将图像保存到数据库中

$img_data = file_get_contents(Input::file('imgInp'));
        $base64 = base64_encode($img_data);
        $admin = Admin::find(25);
        $admin->picture = $base64;
        $admin->update();
        echo $base64;

->update() 函数似乎对我的数据库没有任何作用,因为图片字段始终为 NULL,尽管 $base64 有数据。 mysql 数据库中的列类型是longblob,我已经尝试过->save(),但仍然没有任何内容保存到数据库中。请帮忙

【问题讨论】:

  • 任何错误/异常?
  • @André 我已经在问题中说过我已经尝试过->save(),但没有任何东西保存到我的数据库中
  • 您不应将任何图像作为 base64 存储在数据库中。只需将 img 保存到您的资产文件夹并存储 img 的路径即可。
  • @CarlosGoce 我希望自己保存图像。
  • @CarlosGoce 好的,这听起来不错,你知道在 laravel 中怎么做吗?

标签: php mysql laravel laravel-4


【解决方案1】:

图片上传到一个临时文件夹,所以:

#Get the path to the uploaded img
$filePath = Input::file('imgInp')->getRealPath();
$fileName = Input::file('imgInp')->getClientOriginalName();
$extension = Input::file('imgInp')->getClientOriginalExtension();

#Lets add the extension to the file name
$fileNameWithExtension = $fileName . '.' . $extension;

#Create the folder img/uploaded on your public folder!
$destination = public_path('img/uploaded/' . $fileNameWithExtension);

#Copy the img to your desired destination
#copy ( $filePath, $destination );

#Instead of the copy function you can use this laravel function
Input::file('imgInp')->move($destination);

#Save on database the path to your img

$admin = Admin::find(25);
$admin->picture = $destination;
$admin->update();

我希望它有效。没试过

然后,如果您想显示您的图像,只需执行以下操作:

$admin = Admin::find(25);

#Pass the variable to your view and them, if you use blade templating system:
<img src="{{asset($admin->picture)}}">

#If you are not using blade do it this way
<img src="<?php echo asset($admin->picture); ?>">

【讨论】:

  • 我的destination folder 应该在哪里?在视图中?在approot?
  • 视情况而定。如果图像不是私有的,您可以将它们保存在公共文件夹中,否则,将它们保存在存储文件夹中。您可以使用内置函数 public_path('desired/destination/inside/public/folder') 或 storage_path('desired/destination/inside/storage/folder')。
  • 您能否更新您的答案并使用必要的代码复制到公共文件夹?
  • 我更新了答案。我建议你检查 Laravel Helper 函数laravel.com/docs/helpers
  • 感谢更新,一切正常。除了文件的扩展名。该文件被保存,没有扩展名。我复制了你的代码,只需将 $filename 更改为 admin_20 +1 给你并接受答案
猜你喜欢
  • 2021-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
相关资源
最近更新 更多