我用 laravel 5.8 开发了一个站点,我想使用 slugs 而不是 id。我知道我有两个表服务和类型服务。服务键在服务类型表中是外来的。我按服务类型检索和显示服务。但在我的网址上显示了类型 ID。我有这个错误缺少 [Route: service] [URI: service/{slug}] 的必需参数。(查看: C:\laragon\www\elbi\resources\views\layouts\partial\nav.blade.php) (查看: C:\laragon\www\elbi\resources\views\layouts\partial\nav.blade. php)表格: public function up() { Schema::create('services', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->timestamps(); }); } public function up() { Schema::create('type_services', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('service_id'); $table->foreign('service_id')->references('id')->on('services')->onDelete('cascade'); $table->string('name'); $table->text('description'); $table->string('image'); $table->timestamps(); }); }楷模<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Service extends Model{ public function typeservice() { return $this->hasMany('App\Typeservice'); }}<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class TypeService extends Model{ /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function service() { return $this->belongsTo('App\Service'); } public function getRouteKeyName() { return 'slug'; }}显示控制器 public function index() { $contacts = Contact::all(); $abouts = About::all(); $services = Service::with('typeservice')->orderBy('name','asc')->get(); $typeservices =TypeService::all(); $makings = Making::all(); $realisations = Realisation::all(); $addresses = Address::all(); return view('index',compact('contacts','services','abouts','typeservices','makings','realisations','addresses')); }
2 回答
小唯快跑啊
TA贡献1863条经验 获得超2个赞
你可以试试Spatie 的 Laravel-Sluggable包。
$service = new Service();
$service->name = 'This is a service';
$service->save();
echo $service->slug; // ouputs "this-is-a-service"
慕森卡
TA贡献1806条经验 获得超8个赞
您可以通过存储slug在数据库中并相应地修改控制器中的查询来做到这一点,可以在保存模型之前设置 Slug,如下所示:
$slug = \Illuminate\Support\Str::slug($service->name);
$service->slug = $slug;
您可以在调用save方法之前手动放置此逻辑或使用Eloquent 事件- 特别是savingevent 。
- 2 回答
- 0 关注
- 155 浏览
添加回答
举报
0/150
提交
取消