LorenzoBerti LorenzoBerti - 22 days ago 8
PHP Question

Laravel 5.1 select field in with function

Can I select value from relationships with function "with" ?
So make something like this:

$test = User::where('id',1)->with(['user_detail' => function($query){
$query->select("detail_1");
}])->get();


Yes I know that I can put select in relation "user_detail" but can I select in with function?

Answer

You can select within with as you made the example given below:

$test = User::where('id',1)->with(['user_detail' => function($query){
    $query->select("detail_1");
}])->get();

But it won't not work (as you commented in other answer) because you've only selected a single property but the foreign key is not available in your select statement. So, make sure that, you also select the related foreign key as well and then it'll work.

In your case, I believe that, you've to also select the user_id in your select for example:

$test = User::where('id',1)->with(['user_detail' => function($query){
    $query->select(
        'user_id', // This is required if this key is the foreign key
        'detail_1'
    );
}])->get();

So, without the foreign key that makes the relation, Eloquent won't be able to load the related models and that's why you get null in your result as you mentioned in other comment.