Ad

I Need To Store The Id In A Selected Row In Laravel

$typ= category3::where('type_name', '=', $request->name)->where('category','=',$request->category)->get();

Above is the code in file to select the row from table category3.

Now what should i do to get the id of that selected row stored to a variable called $type_id?

Ad

Answer

Use pluck() method to select one column. Example:

$typ = category3::where('type_name', '=', $request->name)
    ->where('category','=',$request->category)
    ->pluck('id');

It will return only the value of id from the row matched with your query, if more than one row matched with your query it will return the first row's result. You can use the $typ as $type_id or you can store the query result in $type_id instead of $typ.

Or you can pass all needed columns name in an array inside get() method as a parameter. Example:

$typ= category3::where('type_name', '=', $request->name)
    ->where('category','=',$request->category)
    ->get(['id','otherIfNeeded']); // if no parameter it will return all column's value

It will return a collection of data matched with the query. To retrieve the ids in blade file

@foreach($typ as $type_id)
    {{ $type_id->id }}
@endofreach
Ad
source: stackoverflow.com
Ad