Hey.
The find
method on eloquent queries searches for a post by its primary key (http://laravel.com/api/source-class-Illuminate.Database.Eloquent.Builder.html#52-64), so your SQL from above is
SELECT * FROM posts WHERE id = 1 ORDER BY id asc
I think the following should work instead:
$singlepost = Post::orderBy('id', 'ASC')->first();
$singlepost->delete();
Thanks for your reply. I tried the code you supplied but it threw me a new error:
Call to a member function delete() on null
Looks like you might not have any posts in your database in that case. You could update to the following to catch this:
if ( $singlepost = Post::orderBy('id', 'ASC')->first() )
{
$singlepost->delete();
}
I excluded some code from the script because I didnt think it mattered. This is the full script:
$posts = Post::orderBy('id', 'ASC')->get();
while(count($posts) > 9)
{
$singlepost = Post::orderBy('id', 'ASC')->first();
$singlepost->delete();
}
I tried changing the while to a if statement, no errors where thrown, but it deleted all the posts in the database.
I think your while
statement is wrong - if there are more than 9 posts in the database then it may be a continuous loop.
If you're wanting to delete the oldest 9 posts in the database I'd do something like this:
$posts = Post::orderBy('id','ASC')->take(9)->get();
if ( ! $posts->isEmpty() )
{
foreach ( $posts as $post )
{
$post->delete();
}
}
Additionally, if your Eloquent model uses timestamps then I might switch out id
for created_at
.
Hope that helps.
Sorry for not explaining the purpose probably. The initial idea was to keep deleting posts until there was under 9 posts.
Would this work?
$total_posts = Post::count();
$leave = 8;
if ( $total_posts > $leave )
{
$oldest = Post::orderBy('id','ASC')->take($total_posts - $leave)->get();
foreach ( $oldest as $post )
{
$post->delete();
}
}
It worked perfectly! Thank you very much for your time.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community