Laravel

GET Route in Laravel

Aug 6, 2024, 4:30 PM
Blog Thumbnail

Laravel provides a simple poweful routing system for laravel application . Get Route Use for get request like get data and resources from server.

What is a GET Route?

A GET request is used to get information from server. like blog post , blog category etc.

Defining a GET Route in Laravel

In Laravel, you can define `GET` routes using the Route::get() method. Here’s how you define a simple `GET` route in the routes/web.php file:

             
Route::get('/welcome', function () {
    return 'Welcome to Laravel!';
});
            
        

The above route will return a simple string when the `/welcome` URL is accessed via a `GET` request.

GET Route with Views

Often, `GET` routes return a view rather than just a string. Laravel provides a powerful view rendering system that allows you to pass dynamic data to views. Here’s how you can define a route that returns a view:

            
Route::get('/blog', function () {
    return view('blog.index');
});
            
        

In the above example, the route fetches the blog.index view and returns it when the `/blog` URL is accessed.

GET Route with Data

You can also pass dynamic data to the view using `GET` routes. Here’s an example that retrieves blog posts from a database and displays them:

            
Route::get('/blog', function () {
    $blogs = \App\Models\Blog::all();
    return view('blog.index', compact('blogs'));
});
            
        

This route fetches all blog posts from the database using Eloquent and passes them to the view.

Displaying Data in a View with Tailwind CSS

Let’s now look at how to display the blog posts in a view using Tailwind CSS for styling.

            
        <div class="container mx-auto p-4">
            <h1 class="text-3xl font-bold text-center my-6">Latest Blogs</h1>
        
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                @foreach ($blogs as $blog)
                    <div class="bg-white p-4 rounded-lg shadow-lg">
                        <h2 class="text-xl font-semibold text-gray-800">{{ $blog->title }}</h2>
                        <p class="text-gray-600 my-2">{{ Str::limit($blog->content, 150) }}</p>
                        <a href="/blog/{{ $blog->slug }}" class="text-blue-500 hover:underline">Read More</a>
                    </div>
                @endforeach
            </div>
        </div>
            
        

The code above creates a responsive blog posts using Tailwind's css. The blog title and content snippet are displayed for each blog post.

Conclusion

GET routes in Laravel are essential for retrieving data from the server and displaying it in laravel view and other frontend framework. Get request is very easily get data from server without any perameter and with perameter.