Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

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();
Last updated 2 years ago.
0

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
Last updated 2 years ago.
0

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();
}
Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0

Sorry for not explaining the purpose probably. The initial idea was to keep deleting posts until there was under 9 posts.

Last updated 2 years ago.
0

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();
	}
}
Last updated 2 years ago.
0

It worked perfectly! Thank you very much for your time.

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

thobiasn thobiasn Joined 22 Sep 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.