亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 slugs 而不是 id

使用 slugs 而不是 id

PHP
DIEA 2021-09-18 17:18:49
我用 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"


查看完整回答
反對 回復 2021-09-18
?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

您可以通過存儲slug在數據庫中并相應地修改控制器中的查詢來做到這一點,可以在保存模型之前設置 Slug,如下所示:


$slug = \Illuminate\Support\Str::slug($service->name);

$service->slug = $slug;

您可以在調用save方法之前手動放置此邏輯或使用Eloquent 事件- 特別是savingevent 。


查看完整回答
反對 回復 2021-09-18
  • 2 回答
  • 0 關注
  • 184 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號