Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store single result into variable without using foreach

I would like to store a single result from the database into a variable. I tried it in different ways, but not really getting what I'm looking for. Please see my code below: This is in the controller

public function create()
{
    //
    $user_id = Auth::id();

    $company_id = User::select('company_id')->where('id', $user_id)->first();

    $curriculums = Curriculum::where('company_id','=', $company_id)->get();
    dd($curriculums);


    return view('qualificationheaders.create', ['user_id'=>$user_id]);
}

result from the dd is:

Collection {#2232 ▼ #items: [] }

If I replace $curriculum_id with an actual id, I get the correct result. So I figured it's because $company_id = User::select('company_id')->where('id', $user_id)->first(); doesn't really return a single value even though I put ->first() at the end. Kindly assist. I'm a newbie to laravel

like image 425
kya Avatar asked Aug 12 '26 20:08

kya


1 Answers

you need make some modifications :

public function create()
{
    //
    $user_id = Auth::id();
// it return user not value
    $user = User::select('company_id')->where('id', $user_id)->first();   
// $user->company_id not $user
    $curriculums = Curriculum::where('company_id','=', $user->company_id)->first();
    dd($curriculums);


    return view('qualificationheaders.create', ['user_id'=>$user_id]);
}

EDIT : also you can do another thing :

public function create()
{
    //get company_id 
    $company_id = Auth::user()->company_id;

    $curriculums = Curriculum::where('company_id','=', $company_id)->first();
    dd($curriculums);


    return view('qualificationheaders.create', ['user_id'=>Auth::id()]);
}
like image 91
Mortada Jafar Avatar answered Aug 14 '26 10:08

Mortada Jafar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!