0

I am a native PHP programmer and I started learning Laravel a few days ago. I am struggling with how to get data from the database. Usually (in native), I use a query and OOP to connect to the DB and execute queries, but in Laravel it is a little weird and I don't get it.

Example, I want to get data from the database where user_id = 1.

Last but not least

In vanilla PHP I assigned auto user_id without login by using a session, for example:

if (!isset($_SESSION['user_id'])) {
  $id = // random function to generate random numbers
  $_SESSION['user_id'] = $id;
}

I don't know how to do it in Laravel. Please remember that anything will help me so don't hesitate to tell me.

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
svqo
  • 45
  • 2
  • 8
  • 4
    Laravel has [**great** documentation](https://laravel.com/docs/8.x). Have you read it? [Laracast](https://laracasts.com/topics/laravel) also provides a ton of tutorials on how to get started. – Kirk Beard Jul 22 '21 at 00:21
  • oh thanks, i will read it. – svqo Jul 22 '21 at 00:31

2 Answers2

2

You can use the query builder like:

DB::table('table_name')->where('column', $value)->first();

Example:

DB::table('users')->where('id', 5)->first();

Or you can use Models like:

$user = User::find(user_id);

Example:

$user = User::find(5);

You can find a lot more on the Laravel documentation...

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
2
if (Session::has('user_id')) { // check UserId Exists In The Session
        
} else {
    $id = //rnd function to generate random numbers ;
    Session::put('user_id', $value); // Set Value in Session using put method
}

Also find how to get a value from the session in the Laravel docs.

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
Ankita Dobariya
  • 823
  • 5
  • 14