In this tutorial, we will learn how to write php code in laravel blade file. In laravel blade file we add the php code some different way; just like we use to start @php and @endphp to end the php code.
As a laravel begginer don’t know how to write php code in laravel blade file so we all are search these type question i also search that so don’t worry for thease question because codingdriver team added all these types posts in this blog.
Here we show you two best example to write php in laravel blade files. You must use the first one example to write php code in laravel any version such as laravel 5, laravel 6, laravel 7, laravel 8 or laravel 9 version;
Exaple 1: @php use in laravel blade
We suggest you this example is perfect for add php code in blade file.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
@php
$array = [
"name" => "Test name",
"city" => "Test City",
"mobile" => 9595959595
];
print_r($array );
@endphp
<div class="row">
<p>{{ $array['name'] }}</p>
<p>{{ $array['city'] }}</p>
<p>{{ $array['mobile'] }}</p>
</div>
</body>
</html>
Here if you are using foreach loop and don’t know how to use php variable in blade file. Thats example help you.
Example 2: use @ inside with Loop
Here you can see how to use laravel variable inside php ..
@foreach ($tasks as $task)
@if ($task->due_at) < date(now))
@php $style = 'alert alert-danger'; @endphp
@elseif ($task->pivot->due_at) > date(now))
@php $style = 'alert alert-success'; @endphp
@else
@php $style = ''; @endphp
@endif
@endforeach
Example 3: Using Core PHP Code
The below code is core php so you can use it its working fine but from the point of laravel view above code is best.
<?php
foreach ($tasks as $task) {
if ($task->due_at) < date(now)) {
$style = 'alert alert-danger';
}
elseif {
$style = 'alert alert-success';
}
else {
$style = '';
}
}
?>
Read Here: How to Use If Isset Check in Laravel Blade File
Ii hope this examples help you more.
Thanks so much i was able to fix my error with your code example
I’m not sure where you’re getting your info, but good topic.