Home Javascript How to use Laravel Variable in JQuery?

How to use Laravel Variable in JQuery?

by Shahriar Sagor
use Laravel Variable in JQuery

Hello Dev, Today now in this post i will show you How to use Laravel Variable in JQuery? Sometimes we need to show Jquery value in our laravel application. If you to know How to use Laravel Variable in JQuery? Then i hope you are in right place. Here i will show this example step by step. This is very easy and simple example of How to use Laravel Variable in JQuery?

So let’s start this example:

Example 1:

Blade File Code:
<!DOCTYPE html>
<html>
<head>
    <title>How to use Laravel Variable in JQuery? - CodingsPoint.com</title>
</head>
<body>
</body>
  
@php
    $name = "Shahriar Sagor";
    $number = 27;
@endphp 
  
<script type="text/javascript">
    
    var name = "{{ $name }}";
    console.log(name);
  
    var name = "<?php echo $name ?>";
    console.log(name);
  
    var number = "<?php echo $number ?>";
    console.log(number);
  
</script>
</html>

Example 2:

Controller File Code:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $posts = Post::take(5)->get();   
  
        return view('posts', compact('posts'));
    }
}
Blade File Code:
<!DOCTYPE html>
<html>
<head>
    <title>How to use Laravel Variable in JQuery? - CodingsPoint.com</title>
</head>
<body>
</body>
   
<script type="text/javascript">
    
    var posts = "{{ Js::from($posts) }}";
    console.log(posts);
  
    var posts = ;
    console.log(posts);
    
</script>
</html>

Read Also: php artisan serve not working in Laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like