How to write sql query to laravel?

by elise_daugherty , in category: PHP Frameworks , 14 days ago

How to write sql query to laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 13 days ago

@elise_daugherty 

To write SQL queries in Laravel, you can use the built-in query builder provided by Laravel's Eloquent ORM. Here is an example of how you can write a simple SQL query using the query builder in Laravel:

1
2
3
4
$data = DB::table('users')
            ->select('name', 'email')
            ->where('id', 1)
            ->get();


In this example, we are querying the users table in the database and selecting the name and email columns where the id is equal to 1. The get() method is used to execute the query and retrieve the results.


You can also use raw SQL queries in Laravel by using the DB::raw() method. Here is an example:

1
$data = DB::select(DB::raw("SELECT name, email FROM users WHERE id = 1"));


This will execute the raw SQL query and return the results.


Additionally, you can also use Eloquent ORM to perform database operations in Laravel. Here is an example:

1
$data = User::where('id', 1)->get();


In this example, User is the model representing the users table in the database. We are using the where() method to filter the records based on the id column and then calling the get() method to retrieve the results.


These are some ways you can write SQL queries in Laravel using query builder, raw SQL, or Eloquent ORM.