Nutan Panta
Nutan Panta

Reputation: 69

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

In my controller in finorfail it returns array but instead i want pass package name My controller:

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

My we.php:

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

My Model:

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'];
}

SO i want to pass PackageName instead of array of numbers enter image description here So instead of 1 i want it to be package name in the url

My Migration:

   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();
        });
    }

Upvotes: 0

Views: 77

Answers (1)

STA
STA

Reputation: 34708

You can do it like this :

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,
    ]);
}

The Str::slug method generates a URL friendly "slug" from the given string, so while saving Package_name make an another fileld called slug, where the slug name will be saved :

use Illuminate\Support\Str;

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

// welcome-to-stackoverflow

Upvotes: 1

Related Questions