How to retrieving a list of column values in Laravel 5

If you want to retrieve a collection containing the values of a single column, you may use the pluck method.

Let’s create a pluck method in laravel 5

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use DB;

class PostController extends Controller
{
    public function addPost()
    {
        $titles = DB::table('tbl_add_post')->pluck('title');
        foreach ($titles as $title) {
           echo $title;
        }
    }
}

You may also specify a custom key column for the returned Collection.

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use DB;

class PostController extends Controller
{
    public function addPost()
    {
        $titles = DB::table('tbl_add_post')->pluck('title','slug');
        foreach ($titles as $slug => $title) {
            echo $slug;
        }           
    }
}

Leave a Reply

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