Read

Get all data from model

Get all row of a table corresponding with a Model

MODEL_NAME::all();

Example

Route::get('/name', function () {
    $names = Name::all();
    foreach ($names as $name) {
        echo "ID :".$name->id." ";
        echo "Name :".$name->name;
        echo "<br/>";
    }
});


Fetch first row

MODEL_NAME::first();


Fetch a row by Primary Key

MODEL_NAME::find( ..id.. );

Also multiple row(s) can be fetch by find() method

MODEL_NAME::find( [ 1 , 2 , 3 , .... ] );

you must pass an array in find() method for getting multiple row.


Get row(s) by matching conditional query constraints.

MODEL_NAME::where('column' , 'value')
           ->where('column' , 'value')
           ->where('column' , 'value')
           ...........................
           ...........................
           ->get();

get() method must have to with where() method to fetch data

Example

Fetch row(s) which has active column's value is 1

MODEL_NAME::where('active' , 1)->get()

Fetch row(s) which has active column's value is 1 and role column's value is administration

MODEL_NAME::where('active' , 1)->where('role','administration')->get()


Some fetch filtering methods

first()

This method is used for fetching first row from multiple rows

Fetch first row from all rows

MODEL_NAME::all()->first();

BTW you can easily fetch first row from all rows by this MODEL_NAME::first() :smile:

Fetch first where role is administration

MODEL_NAME::where('role','administration')->first()->get();

Since I used where() method , so I must have to use get() method with it to get row data


limit() / take()

Take a certain number of row(s) from multiple rows

Take 3 row from all rows

MODEL_NAME::all()->limit(3);
MODEL_NAME::all()->take(3);

Example

Fetch first 3 row which has active = 1 and age column's value is between 18 to 25

MODEL_NAME::where('active',1)
          ->where('age' , '>' , 18)
          ->where('age' , '<' , 25)
          ->limit(3)
          ->get();


count()

Get total number of row(s)


Count number of rows

    MODEL_NAME::all()->count();

Count number rows which has active = 1 and age column's value is between 18 to 25

MODEL_NAME::where('active',1)
          ->where('age' , '>' , 18)
          ->where('age' , '<' , 25)
          ->count();


sum('COLUMN_NAME')

Get summation of a certain column

MODEL_NAME::all()
          ->sum('amounts');

max('COLUMN_NAME')

Fetch a row which has maximum value of specific column

MODEL_NAME::where('role','student')
          ->max('CGPA');





Available Methods

https://laravel.com/docs/5.5/eloquent-collections#available-methods

results matching ""

    No results matching ""