I am new to laravel and using simple command to query from database. I am trying to get multiple value from database with same id.
$id = 'P01';
//Get value from database
$fruitname = DB::table('fruits')->where('id', $id)->value('fruitname');
$fruitcolour = DB::table('fruits')->where('id', $id)->value('fruitcolour');
$fruitshape = DB::table('fruits')->where('id', $id)->value('fruitshape');
$updatedat = DB::table('fruits')->where('id', $id)->value('updated_at');
$data = array(
'fruitname' => $fruitname,
'fruitcolour' => $fruitcolour,
'fruitshape' => $fruitshape,
'updated_at' => $updatedat
);
As result, $data can store the value.
But i found out that it takes time to complete the process.
Is there any ways i can optimize the process?
I'm not sure why you're making it more hard than it is, but you can just simply use eloquent in this case:
Provided you already have created the necessary model and adding it in your controller:
use App\Fruits;
Just simply use it in the find method:
public function someMethodName()
{
$id = 'P01';
$fruit = Fruits::find($id);
echo $fruit->fruitname; // and others
}
$fruit = DB::table('fruits')->where('id', $id)->first();
$data = array(
'fruitname' => $fruit->fruitname,
'fruitcolour' => $fruit->fruitcolour,
'fruitshape' => $fruit->fruitshape,
'updated_at' => $fruit->updatedat
);
Or if you have a view, you could just do
$fruit = DB::table('fruits')->where('id', $id)->first();
return view('yourview', compact('fruit'));
And in the view, you can access each of the values like so:
{{ $fruit->fruitname }}
{{ $fruit->fruitcolor }}
In your controller add function
public function function_name(Fruit $fruit)
{
return view('your_view_name', compact('fruit'));
}
In web file set your route as
Route::get('/fruit/{fruit}','YourControllername@methodName')->name('show');
At the time of setting route
<a href="{{route('show', ['fruit' => $id])}}">Show</a>
in View file get data as
{{ $fruit->fruitname }}
{{ $fruit->fruitcolor }}