如何在控制器中传递数据库数据而不是数组

How to pass a database data instead of array in the controller

在我的控制器中 finorfail 它 returns 数组但是我想传递包名 我的控制器:

    public function package($package){
        $package = Packages::findOrFail($package);
        return view('pages.package',[
            'package' => $package,
        ]);
    }

我的we.php:

Route::prefix('/packages')->group(function() {
    Route::get('/', 'PackageController@packages')->name('package.show');
    Route::get('/{package}', 'PackageController@package')->name('package.show');
});

我的模特:

class Packages extends Model
{
    protected $table = 'packages';

    protected $fillable = ['Package_Banner_Image','Package_Image','Package_Type','Package_Name','Package_Short_Description','Package_Price','Package_Duration','Package_Level','Package_Location'];
}

所以我想传递 PackageName 而不是数字数组 所以我希望它成为 url

中的包名称而不是 1

我的迁移:

   public function up()
    {
        Schema::create('pages', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')->nullable();
            $table->string('slug')->nullable();
            $table->text('description')->nullable();
            $table->string('image')->nullable();
            $table->string('meta_title')->nullable();
            $table->text('meta_description')->nullable();
            $table->integer('main')->nullable();
            $table->string('publish')->nullable();
            $table->timestamps();
        });
    }

你可以这样做:

public function package($package)
{
   $package = Packages::where('Package_name', $package)->first();
  
    if(empty($package)) { 
      return abort(404); // if $package is empty, it will return 404
    } 

    return view('pages.package',[
         'package' => $package,
    ]);
}

Str::slug 方法从给定的字符串生成一个 URL 友好的 "slug",因此在保存 Package_name 的同时创建另一个名为 slug 的 fileld,将保存 slug 名称的位置:

use Illuminate\Support\Str;

$slug = Str::slug('welcome to Whosebug', '-');

// welcome-to-Whosebug