Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 Array to string conversion exception

I am trying to break down a string into an array and then print the values on the screen. Here is the string that i am trying to break:

"Cog|Condor"

"|" using this to split it. Here is how I am doing it:

<?= $arrays = explode('|', $b->brand); foreach($arrays as $array){echo $array;}  ?> 

But i keep getting this exception:

    2/2) ErrorException
Array to string conversion (View: D:\Code\PHP\Code\CrownBillingSystem\resources\views\pages\print.blade.php)
in 6e7ee4930110d4a26a3e31e0ddfe8b87849a1319.php (line 93)
at CompilerEngine->handleViewException(object(ErrorException), 1)
in PhpEngine.php (line 44)
at PhpEngine-

I cannot figure out what is wrong here.

like image 763
Muhammad Muneeb ul haq Avatar asked Dec 14 '22 21:12

Muhammad Muneeb ul haq


2 Answers

While the other answers are not incorrect, Blade has been designed to eradicate the use of PHP tags. Blade functions allow you to do everything.

The error being produced here is that <?= is shorthand for <php echo. So your code will render as echo $arrays in pseudo code terms which is where the PHP is breaking because you cannot echo an array.

To better your code in this instance, you should be manipulating as much of the data as possible in the controller which is also mentioned here in the blade documentation.

Might I suggest modifying your code, to produce the same result, but using blade.

@php 
    $arrays = explode('|', $b->brand); 
@endphp

@foreach($arrays as $array)
    {{ $array }}
@endforeach

The above snippet will produce the same results as intended.

An even better way of doing it, and to further your understanding would be to return the view from the controller, and pass in $arrays predefined. Something like this:

public function echoArrays()
{
    $b = Object::find(1); //or however you get $b
    $arrays = explode('|', $b->brand); 
    return view('view1', compact('arrays');
}

The above will allow you to use the code snippet 2 up, but without the @php ...@endphp tags, and just use the @foreach() ... @endforeach

like image 91
mbozwood Avatar answered Dec 22 '22 01:12

mbozwood


You can't put multiple statements in <?= ... ?> blocks - it's short-hand for echo, so your code expands to

<?php
  echo $arrays = explode('|', $b->brand); // This is what's causing your error

  foreach($arrays as $array){echo $array;}
?>

If you want to perform operations as well as output, you just need to use full PHP tags:

<?php $arrays = explode('|', $b->brand); foreach($arrays as $array){echo $array;}  ?> 
like image 22
iainn Avatar answered Dec 22 '22 00:12

iainn