DolDurma
DolDurma

Reputation: 17289

Laravel find data by model

I'm trying to debug data when i try to edit some column on database for example id such as 1, when i run this url on address bar:

http://127.0.0.1:8000/content_category/1/edit

i get this result:

ContentCategories {#246 ▼
  #table: "contents_categories"
  #guarded: array:1 [▶]
  #connection: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: false
  +wasRecentlyCreated: false
  #attributes: []
  #original: []
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
}

data is null in this result and i don't have any information about id=1

this column of data is exist on database and i checked that with phpmyadmin, my edit function on controller is:

public function edit(ContentCategories $contentCategories)
{
    dd($contentCategories);
}

and Model in project:

class ContentCategories extends Model
{
    protected $table = 'contents_categories';
    protected $guarded = ['id'];
}

route:

Route::resource('content_category', 'ContentCategoriesController');

Upvotes: 1

Views: 1017

Answers (2)

lagbox
lagbox

Reputation: 50491

You will need to update your method signatures to be able to use implicit route model binding here.

"Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name." Laravel 5.5 Docs - Routing - Implicit Model Binding

public function edit(ContentCategories $content_category)

This matches the route parameter name to your type hinted parameter name. This will allow for the binding to happen. Without this matching of the names of these parameters the typehinted parameter you have is being resolved as a new instance of that model via dependency injection. It has to resolve the dependency so you get a new model instance because it doesn't know that it is the parameter you want the binding for.

Additional information:

"By default, Route::resource will create the route parameters for your resource routes based on the 'singularized' version of the resource name."

Laravel 5.5 Docs - Controllers - Resource Controllers - Naming Resource Route Parameters

Upvotes: 1

Abid Raza
Abid Raza

Reputation: 755

Try this in your controller edit method

public function edit($id)
{
    $contentCategories = ContentCategories::find($id);
    dd($contentCategories);
}

Upvotes: 0

Related Questions