Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

php - Laravel Eloquent::Find() returning NULL with an existing ID

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 IlluminateDatabaseEloquentModelNotFoundException;

 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 IlluminateSupportFacadesRedirect;
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 IlluminateDatabaseEloquentSoftDeletingTrait;
use IlluminateDatabaseEloquentModelNotFoundException;

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:

  1. Made nullable 'deleted_at' column.

  2. Set all wrong 'deleted_at' timestamps to NULL.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...