4

I'm using from laravel localization to switch between two languages and dynamically retrieve the data according to the selected language. the database field names are name_en, detail_en in English Language and name_pe, detail_pe in Persian Language, So I want to get the en and pe from session and save into variable $lng and then concatenate it to the database field in blade file.

  @php
    $lng = Session::get('local');
    // will return en or pe
    @endphp

@foreach ($products as $product)
<tr>
    <td>
        <input class="self_delall" id="self_delall" type="checkbox" name="delid[]" value="{{ $product->id }}"/>
    </td>
    <td>{{ ++$i }}</td>
    <td>{{ $product->name_.$lng }}</td>
    <td>{{ $product->detail_.$lng }}</td>
    <td>
        <a class="btn btn-info" href="{{ route('products.show',$product->id) }}">Show</a>
        @can('product-edit')
        <a class="btn btn-primary" href="{{ route('products.edit',$product->id) }}">Edit</a>
        @endcan

        @can('product-delete')
            <a class="btn btn-danger" href="delete/{{ $product->id }}/1">Delete</a>
        @endcan
    </td>
</tr>
@endforeach 

So it return only the value of $lng instead of retrieve the database field value the output is here: enter image description here

1 Answer 1

3

I think the problem is in the way you call the property of the object. You want to get the name_en or name_pe from $product object.

When you do $product->name_.$lng, what actually happen is the PHP get the value of $product->name_ and then add it with the value in $lng. In this case, the $product->name_ is NULL and $lng is en or pe that why the output is either en or pe.

So, the solution is, you should change the way you call the attribute with $product['name_' . $lng] or prepare a variable $column = 'name_' . $lng; $product->$column; or you can do this $product->{'name_' . $lng}.

You can refer the operation from this post.

Sign up to request clarification or add additional context in comments.

2 Comments

Sure, I'm glad it helps you!
That last bit with the $product->{'name_' . $lng} was the life saver! Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.