How to do query & show the result in laravel?


by dedrick , in category: PHP Frameworks , a month ago

How to do query & show the result in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , a month ago


To perform a query and show the result in Laravel, you can use Eloquent ORM which allows you to interact with your database using PHP objects. Here's how you can do it:

  1. Define a model: Create a model for the table you want to query. You can generate a model by running the following command in your terminal:
php artisan make:model ModelName

  1. Perform a query: You can perform a query using Eloquent ORM methods such as all(), find(), where(), orderBy(), etc. For example, to retrieve all records from a table named users, you can use the following code:
$users = User::all();

  1. Show the result: You can pass the result to your view to display it. For example, in your controller method, you can pass the $users variable to your view file like this:
return view('view-name', ['users' => $users]);

  1. In your view file, you can loop through the results and display the data. For example:
@foreach($users as $user)
    <p>{{ $user->name }}</p>
    <p>{{ $user->email }}</p>

This is a basic example of how to query and display data using Laravel. You can customize the query as per your requirements using Eloquent ORM methods.