用户可以上载image
,我想捕获所提供的$request
图片标题并将其转换为slug
并将其保存到Database
UploadScreenShotController @ upload:
public function upload(Request $request)
{
if (!auth()->check()) return $this->with('error', 'Session has ended. Please refresh the page and try again.');
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->image;
$filename = $image->getClientOriginalName();
$request->image->move(public_path('images/tcpa/screenshots'), $filename);
return back()
->with('success', 'You have successfully uploaded an image.')
->with('image', $filename);
}
我的表单:
{!! Form::open(['method' => 'POST', 'files' => 'true', 'route' => ['admin.sms.tcpa-upload-screenshot']])!!}
{!! Form::file('image') !!}
{!! Form::submit('Upload File') !!}
{!! Form::close() !!}
此function
获得image
名称,但不会将其转换为slug
,也不会保存在Database
中。
如何将image
标题转换为slug
并将其保存到Database
?
您可以使用Sluggable包在项目中创建slug。该软件包提供了一个特征,当保存任何Eloquent模型时,该特征将生成唯一的段。
安装您可以通过composer安装该软件包:
`composer require spatie/laravel-sluggable`
这里是如何实现特征的示例:
namespace App;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
use Illuminate\Database\Eloquent\Model;
class YourEloquentModel extends Model
{
use HasSlug;
/**
* Get the options for generating the slug.
*/
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug');
}
}
并且还记得在数据库表中添加一个子字段。使用Laravel Migration编辑当前表格。
示例::
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateYourEloquentModelTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('your_eloquent_models', function (Blueprint $table) {
$table->increments('id');
$table->string('slug'); // Field name same as your `saveSlugsTo`
$table->string('name');
$table->timestamps();
});
}
}
然后,如果您想使用该段代码作为路由名称,请记住在模型文件中使用Laravel的隐式路由模型绑定:
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
我认为这会帮助您
放置'enctype'=>'multipart/form-data'
{!! Form::open(['method' => 'POST', 'files' => 'true','enctype'=>'multipart/form-data', 'route' => ['admin.sms.tcpa-upload-screenshot']])!!}
如果可以在模型中使用boot
方法进行此操作。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class YourEloquentModel extends Model
{
protected static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->slug = Str::slug($model->name, '-');
});
}
}
@NIVED KRISHNA可以显示他的答案的其余内容;如:迁移,路由模型绑定。