Ad

What Is The Best Way To Return More Values With Laravel From Controller To A View?

- 1 answer

I've got some trouble by passing 2 values to a view, I'm using the code below, and tried several things like passing it in a array.

My controller:

public function user(User $profile)
{

    $fdate = $profile->geboortedatum;
    $tdate = date('Y-m-d');
    $datetime1 = new DateTime($fdate);
    $datetime2 = new DateTime($tdate);
    $interval = $datetime1->diff($datetime2);
    $years = $interval->format('%y');//now do whatever you like with $years
    //dd($y);





return view('profile.profile', compact('profile'));
}  

My view:

<div>
    <row>
        <div>Naam: </div>
        <div>{{$profile->name}}</div>
    </row>
    <row>
        <div>Geslacht: </div>
        <div>{{$profile->geslacht}}</div>
    </row>
    <row>
        <div>Op zoek naar: </div>
        <div>{{$profile->partnergeslacht}}</div>
    </row>
    <row>
        <div>Leeftijd: </div>
        <div>{{$years}}</div>
    </row>
</div>

I would like to make it possible to return the value $years and compact('profile') from the controller to my view. I tried using a array and pass both values to the view but that didn't work out well. Does someone know some better practices from passing more values at once? That might be useful for me to know in the future too.

Thanks for helping :)

Dave

Ad

Answer

Try using an associative array rather than compact

public function user(User $profile)
{
    ...
    return view('profile.profile', [
        'years' => $years,
        'profile' => $profile
    ]);
}

Example

You are now able to access these variables in your view like so:

{{ $profile }}

@foreach($years as $year)
    {{ $year }}
@endforeach
Ad
source: stackoverflow.com
Ad