I want to include external PHP file ( pdate.php
) in Laravel and use it in blade.php
file. How can I do it?
The PHP file imported in app\\date\\pdate.php
folder and by using app_path()
function in controller I try to send it in blade.php
but there is error.
public function index(){
include_once(app_path() . '/date/pdate.php');
return view('/cashWithdraw/create');
}
When I use one variable of that file in blade.php
I will get this error.
Undefined variable: today (View: E:\\laravelProject\\deal\\resources\\views\\cashWithdraw\\create.blade.php)
In composer.json
file you just add needed files in “autoload” section – in a new entry called files
:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/date/pdate.php"
]
},
after that run this command composer dump-autoload
now you can use any function in this file globally
This can easily be done using the blade
@include()
helper. If you save your file as a pdate.blade.php
file, for example in resources/views/date
, then you can include it as follows:
Inside of cashWithdraw/create.blade.php
:
@include("date/pdate")
The only catch is that the variables available in pdate.blade.php
need to be defined, but that can be done in a number of ways:
Directly in pdate.blade.php
:
@php $today = \Carbon\Carbon::now(); @endphp
In the controller that returns create.blade.php
:
public function index(){
$today = \Carbon\Carbon::now();
return view('cashWithdraw.create')->with(["today" => $today]);
}
In the @includes
within create.blade.php
:
@include("date/pdate", ["today" => \Carbon\Carbon::now()])
You aren't passing any variables into your view. You will need to pass any variables generated by pdate into the view.
public function index(){
include_once(app_path() . '/date/pdate.php');
return view('/cashWithdraw/create', [
'today' => $today
]);
}
The only variables that will be available in your blade are the ones you pass in there.
If your file is a class, you can inject it into a view by using service injection as follows:
@inject('pdata', 'app\date\pdate')
then invoke any method. Assuming your class has one like getMyDate:
<div class="anything">
{{ $pdata->getMyDate() }}
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.