Database Eloquent ORM Reading / Finding with Constraints

In your routes you can test Eloquent reading and finding statements. First include your model to reference, then write your read statements:

use App\Models\Post;

/*
|--------------------------------------------------------------------------
| ELOQUENT ORM (Object Relational Model)
|--------------------------------------------------------------------------
*/

Route::get('/all', function(){
    $posts = Post::all();
    foreach($posts as $post){
        return $post->title;
    }
});

Route::get('/find', function(){
    $post = Post::find(2);
    return $post->title;
});

Route::get('/findwhere', function(){
    $posts = Post::where('id',2)->orderBy('id','desc')->take(1)->get();
    return $posts;
});

Route::get('/findorfail', function(){
    $posts = Post::findOrFail(1);
    return $posts;
});

Route::get('/firstorfail', function(){
    $posts = Post::where('users_count','<',50)->firstOrFail;
    return $posts;
});

The find condition needs the ID of the row in database. The where condition is also looking for the ID of the row (though could look for anything).

Leave a Reply

Your email address will not be published. Required fields are marked *