How to do query & show the result in laravel?

Member

by dedrick , in category: PHP Frameworks , 5 months ago

How to do query & show the result in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 5 months ago

@dedrick 

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:
1
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:
1
$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:
1
return view('view-name', ['users' => $users]);


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


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.