Laravel Eloquent::Find() returning NULL with an existing ID
Solution 1
Check you are getting Input::get('siteId')
correctly. if you are getting it then try to convert it into integer i.e
$iSiteToDelete = intval(Input::get('siteId'));
Solution 2
You're not returning your model.
var_dump
prints output and returns nothing.
do this instead:
dd($oSite); // stands for var_dump and die - a helper method
and even better, simply return the model:
return $oSite; // will be cast to JSON string
Comments
-
zedee almost 2 years
It's pretty straightforward as it's the most basic thing but I don't know what I'm missing:
Having a model called
Site
I'm using Eloquent ORM, so when I call (in a controller)
$oSite = Site::find(1)
and then
var_dump($oSite);
It returns a value of
NULL
.But when I check the database, the table 'sites' actually contains the following item:
id: 1 user_id: 1 name: test
In my
Site
model I have the following code:use Illuminate\Database\Eloquent\ModelNotFoundException; Class Site extends Eloquent { protected $table = 'sites'; protected $fillable = ['user_id', 'name']; }
Instead, if I gather the item with the following:
$oSite = DB::table('sites') ->where('id', 1) ->first();
It works and I get the correct register.
What I'm doing wrong? Which part of the documentation I didn't get?
EDIT:
Model code can be checked above.
Controller:
use Illuminate\Support\Facades\Redirect; class SiteManagementController extends BaseController { ... public function deleteSite() { if (Request::ajax()) { $iSiteToDelete = Input::get('siteId'); $oSite = Site::find($iSiteToDelete); return var_dump($oSite); } else { return false; } } }
EDIT 2: (SOLVED)
Real reason why wasn't working:
I had originally in my model code the following:
use Illuminate\Database\Eloquent\SoftDeletingTrait; use Illuminate\Database\Eloquent\ModelNotFoundException; Class Site extends Eloquent { protected $table = 'sites'; use SoftDeletingTrait; protected $dates = ['deleted_at']; protected $fillable = ['user_id', 'name']; }
Problem was I added a '
deleted_at
' column after I started the project and when I applied migrations, I didn't have softdeleting enabled. Obviously, I did a second error, forgetting to enable 'deleted_at
' to be nullable, hence all inserts went had a wrong timestamp (0000-00-00 ...).Fix:
Made nullable '
deleted_at
' column.Set all wrong '
deleted_at
' timestamps toNULL
.
-
zedee over 9 yearsYes, after var_dumping Input::get('siteId') I got the correct value.
-
Anand Patel over 9 yearsare you getting integer value in var_dump?
-
Anand Patel over 9 yearslink please check this link
-
zedee over 9 yearsChecked the link. And no, Input::get('siteId') returned a string, instead of intval
-
zedee over 9 yearsyes, it is working now, but not because of the typechange. Now Site::find($iSiteToDelete) is working even being $iSiteToDelete is actually a string. What did happen? I really have no idea.