PHP has finished doing its work even before the page hits your browser, so passing a variable from Javascript to PHP without doing another request is simply impossible. Consider
A] Moving your loop to Javascript. Consider using some UI library like Vue.js, Angular or React.
B] Move the contents of myJsVar
to PHP. If it depends on user input or browser rendering, that impossible.
C] Performing the rendering logic through an Ajax-request
$.ajax[{
type: 'GET',
url: myUrl,
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {value: myJsVar},
success: function [response] {
$[someContainer].html[response];
}
}];
And in your controller:
public function prod[]
{
$value = Request::get['value'];
return view['view-with-a-loop']->with['value', $value];
}
Be careful with the latter method XSS-wise.
var id = $['#recordID'].val[];
var url = '{{ route["deleteRecord", ":id"] }}';
url = url.replace[':id', id];
//Call ajax
$.ajax[{
type : "POST",
url : url,
success:function[response]{
console.log[response];
}
}];
Route::post['/delete-record/{id}', [RecordController::class, 'delete']]->name['deleteRecord'];
//localhost:8000/delete-record/1
You can pass javascript value to laravel route using replace method on url variable and assign to url parameter of ajax method.
- Table of contents
- Laravel blade pass Javascript variable in php
- Pass variable from blade to controller Laravel
- Laravel 7.x and 6.x Passing Variable to Javascript Example
- Blade Templates
- Questions
Laravel blade pass Javascript variable in php
var myJsVar = 100; @for [$i = 0; $iajax[]] { $ajax = "AJAX"; dd[$ajax]; } else { $ajaxN = "NO Ajax"; dd[$ajaxN]; } }
$.ajax[{ type: 'GET', url: myUrl, headers: {'X-Requested-With': 'XMLHttpRequest'}, data: {value: myJsVar}, success: function [response] { $[someContainer].html[response]; } }];
public function prod[] { $value = Request::get['value']; return view['view-with-a-loop']->with['value', $value]; }
@extends['layouts.app'] @section['javascript'] var myInteger = {!! $myInteger !!}; var myString = '{!! $myInteger !!}'; var myObject = {!! json_encode[$models] !!}; @endsection @section['content'] ... @endsection
@yield['content'] @yield['javascript']
Pass variable from blade to controller Laravel
@php echo App\Http\Controllers\HomeController::getUserByID[1]; @endphp
public static function getUserByID[$id]{ $user = User::findOrFail[$id]; return $user; }
{"id":1,"name":"john","email":"[email protected]","email_verified_at":"2021-08-02T00:38:40.000000Z","created_at":"2021-08-02T00:38:40.000000Z","updated_at":"2021-08-02T00:38:40.000000Z"}
use App\Http\Controllers\HomeController; Route::get['user/{id}/{name}', [HomeController::class, 'getUserDetail']]->name['user.detail'];
public function getUserDetail[$id, $name]{ echo 'User ID = '. $id. "
"; echo 'User Name = '. $name; }
@php $userID = 1; $name = 'summer'; @endphp Get user Deatails
User ID = 1User Name = summer
Laravel 7.x and 6.x Passing Variable to Javascript Example
public function index[]{ $users = User::get[]; return view['users.index', compact['users']];}
var users = {!! json_encode[$users->toArray[]] !!}; console.log[users];
Blade Templates
Route::get['/', function [] { return view['greeting', ['name' => 'Finn']];}];
Route::get['/', function [] { return view['welcome', ['name' => 'Samantha']];}];
Hello, {{ $name }}.
The current UNIX timestamp is {{ time[] }}.
;
var app = {{ Illuminate\Support\Js::from[$array] }};
var app = {{ Js::from[$array] }};
@verbatimHello, {{ name }}.@endverbatim
@if [count[$records] === 1] I have one [email protected] [count[$records] > 1] I have multiple [email protected] I don't have any [email protected]
@unless [Auth::check[]] You are not signed [email protected]
@isset[$records] // $records is defined and is not [email protected] @empty[$records] // $records is "empty"[email protected]
@auth // The user is [email protected] @guest // The user is not [email protected]
@auth['admin'] // The user is [email protected] @guest['admin'] // The user is not [email protected]
@production // Production specific [email protected]
@env['staging'] // The application is running in "staging"[email protected] @env[['staging', 'production']] // The application is running in "staging" or "production"[email protected]
@hasSection['navigation']@yield['navigation']@endif
@sectionMissing['navigation']@include['default-navigation']@endif
@switch[$i] @case[1] First case... @break @case[2] Second case... @break @default Default [email protected]
@for [$i = 0; $i < 10; $i++] The current value is {{ $i }}@endfor @foreach [$users as $user]This is user {{ $user->id }}
@endforeach @forelse [$users as $user]
No users
@endforelse @while [true]I'm looping forever.
@endwhile@foreach [$users as $user] @if [$user->type == 1] @continue @endif
@foreach [$users as $user] @continue[$user->type == 1]
@foreach [$users as $user] @if [$loop->first] This is the first iteration. @endif @if [$loop->last] This is the last iteration. @endifThis is user {{ $user->id }}
@endforeach
@foreach [$users as $user] @foreach [$user->posts as $post] @if [$loop->parent->first] This is the first iteration of the parent loop. @endif @[email protected]
@php $isActive = false; $hasError = true;@endphp $isActive, 'text-gray-500' => ! $isActive, 'bg-red' => $hasError,]]>
active]] />
@foreach [$product->versions as $version] {{ $version }} @endforeach
isNotEmpty[]]>Submit
@include['shared.errors']
@include['view.name', ['status' => 'complete']]
@includeIf['view.name', ['status' => 'complete']]
@includeWhen[$boolean, 'view.name', ['status' => 'complete']] @includeUnless[$boolean, 'view.name', ['status' => 'complete']]
@includeFirst[['custom.admin', 'admin'], ['status' => 'complete']]
@each['view.name', $jobs, 'job']
@each['view.name', $jobs, 'job', 'view.empty']
@once @push['scripts'] // Your custom JavaScript... @[email protected]
@pushOnce['scripts'] // Your custom JavaScript... @endPushOnce
@php $counter = 1;@endphp
{{-- This comment will not be present in the rendered HTML --}}
php artisan make:component Alert
php artisan make:component Forms/Input
php artisan make:component forms.input --view
use Illuminate\Support\Facades\Blade; /** * Bootstrap your package's services. */public function boot[]{ Blade::component['package-alert', Alert::class];}
use Illuminate\Support\Facades\Blade; /** * Bootstrap your package's services. * * @return void */public function boot[]{ Blade::componentNamespace['Nightshade\\Views\\Components', 'nightshade'];}