Ad

Add Items To Query Result - Laravel

I'm slowly moving my API to Laravel and coming to grips with the Query Builder.

I'm trying to achieve this:

$data = array();

$query = "SELECT * FROM blog_posts WHERE post_type = 3 AND post_status = 1  ORDER BY id DESC";
$result = mysqli_query($cms_connection, $query);
if($result) {
    while($row = mysqli_fetch_assoc($result)) {
        $row['post_seo'] = seoUrl($row['post_title']);
        $data['data'][] = $row;
    }
    $data['success'] = true;
    $response = json_encode($data);
}

My problem isn't necessarily with getting the query, but as you can see I'm using the result of the query and then injecting it back into the final array.

So essentially, I'm fetching rows, transforming some of the attributes fetched, and then injecting the newly created attributes into the resulting array.

This is what I have so far:

$posts = DB::table('blog_posts')
    -where(['post_type' => 1, 'post_status' => 1)
    ->orderBy('id', 'desc')
    ->take(5)->get();
Ad

Answer

You could do it this way

// get your data (yours part of code)

$posts = DB::table('blog_posts')
-where(['post_type' => 1, 'post_status' => 1])
->orderBy('id', 'desc')
->take(5)->get();

// add post_seo

foreach ($posts as $post) {
   $post->post_seo = seoUrl($post->post_title);
}

// set result array

$data['data'] = $posts;
$data['success'] = true;

// response

$response = response()->json($data);

// or in case you want to return it just

return response()->json($data);

EDIT

You could do it also a bit better, using Eloquent. If you have such model (you need to add valid namespaces and use statements)

class BlogModel extends Model 
{
   protected $table = 'blog_posts';
   protected $appends = ['post_seo'];

   public function getPostSeoAttribute($value)
   {
       return seoUrl($this->post_title);
   } 
}

(added accessor to post_seo attribute and added post_seo to results when converting to array)

You can now do (shorter syntax than in previous example):

// get your data

$posts = BlogPost::where('post_type',1)
->where('post_status',1)
->orderBy('id', 'desc')
->take(5)->get();

// response

$response = response()->json(['data' => $posts, 'success' => true]);
Ad
source: stackoverflow.com
Ad