moh_abk
moh_abk

Reputation: 2164

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();

Upvotes: 3

Views: 12241

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111869

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]);

Upvotes: 9

Related Questions