Concatenation with Blade in Laravel

51,205

Solution 1

Try to do this:

{{ $rs->${$item.'_data'} }}

http://php.net/manual/en/language.variables.variable.php

Solution 2

lets say you are retrieving a single record 'task', and this record has variables called 'var1','var2','var3' ... all the way to 'var16'.

you can echo those variables in your blade file like so:

@for($y=1; $y<=16; $y++)
 {{ $task->{'var'.$y} }}
@endfor
Share:
51,205
ProEvilz
Author by

ProEvilz

Updated on May 18, 2020

Comments

  • ProEvilz
    ProEvilz almost 4 years

    I'm trying to access a table column in my ItemController. In this instance, I wish to use the values in my array + a concatenated string to for the column name.

    ItemController.php ....

    public function displayItems() {
       $itemsList = array('Alpha','Bravo','Charlie','Delta');
       //$results = returned mysql row here
       return view('items', ['rs' => $results, 'items' => $itemsList]);
    }
    

    page.blade.php

    @foreach ($items as $item)
      //$item is used elsewhere too, so keep $item
      {{$rs->$item.'_data'}}
    @endforeach
    

    Desired output:

    $rs->Alpha_data;
    $rs->Delta_data;
    etc
    

    How can I dynamically set a variable for $rs->name ?

  • ProEvilz
    ProEvilz about 8 years
    What would be the best way to also call strtolower() on $item.'_data' ?
  • Alexey Mezenin
    Alexey Mezenin about 8 years
    Try {{ $rs->${strtolower($item).'_data'} }}.
  • geisterfurz007
    geisterfurz007 almost 5 years
    The . for concatenation is already used in the original post. Joining the strings itself is not the issue here as you can see with the accepted answer. As this answer does not really address this questions problems, you might want to remove it.
  • fahdshaykh
    fahdshaykh over 2 years
    i have something like this. $category->category->category->name and how do i concatenate like this {{ $rs->${$item.'_data'} }} thanks if any answer on time.