Abdelouahad Elfihri
Abdelouahad Elfihri

Reputation: 23

How to write PHP code inside blade template

In my Laravel blade template, I have a table in which I want to add another column after this code

<td>{{format_price($mission->amount)}}</td>

I added this :

    @php
        $amount_to_be_collected = DB::table('shipments')
        ->select('amount_to_be_collected')
        ->where('mission_id', $mission->id)
        ->get();
    @endphp

<td>{{format_price($amount_to_be_collected)}}</td>

What is wrong with this code?

Upvotes: 1

Views: 1155

Answers (2)

N69S
N69S

Reputation: 17205

First of all, You should not put DB query code in your blade.

Now, when you run a query using eloquent and call get(), the response is a Collection::class instance that can be treated as an array but cannot be automatically transformed into a number/string.

If you only need the value of on field for one entry, use value() instead.

$amount_to_be_collected = DB::table('shipments')
    ->where('mission_id', $mission->id)
    ->value('amount_to_be_collected');

Upvotes: 2

Amir Khan
Amir Khan

Reputation: 441

Note: It is not good to use db queries in blade views, you can also use helper

Try this before using DB facade you need to call this class in blade view Running Database Queries

use Illuminate\Support\Facades\DB;

Upvotes: 0

Related Questions