app/Http/routes.php app/Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [ // it's safe to do Mass Assignment for the following values
'title',
'content'
];
}
<?php
use App\Post; // importing Post model
// create
Route::get('/create', function() {
Post::create(
[
'title' => 'the create method',
'content' => 'Wow, I am learning a lot with Edwin Diaz'
]
);
return "Record created!";
});
// update
Route::get('/update/{id}', function($id) {
Post::where('id', $id)->where('is_admin', 0)->update(
[
'title' => 'New PHP Title',
'content' => 'I love my instructor'
]
);
return "Record updated!";
});
// delete
Route::get('/delete/{id}', function($id) {
$post = Post::find($id);
$post->delete();
return "Record deleted!";
// Post::where('is_admin',0)->delete(); // other option
});
// delete (soft) *Must be using 'SoftDeletes' in Model
Route::get('/softdelete/{id}', function($id) {
$post = Post::find($id);
$post->delete();
return "Record (soft) deleted!";
});
// read
Route::get('/read', function() {
$posts = Post::all(); // pulls all records
foreach($posts as $post) {
return $post->title;
}
});
Route::get('/find/{id}', function($id) {
$post = Post::find($id); // pulls all records
return $post->title;
});
Route::get('/find/id/{id}', function($id) {
$posts = Post::where('id', $id)->orderBy('id', 'desc')->take(1)->get();
return $posts; // returns json object
});
Route::get('/find/more/{id}', function($id) {
$posts = Post::findOrFail($id);
return $posts;
// $posts = Post::where('users_count', '<', 50)->firstOrFail();
});
// read a (soft) deleted item *Must be using 'SoftDeletes' in Model
Route::get('/readsoftdelete/{id}', function($id) {
// $post = Post::find($id); // does not work
$post = Post::withTrashed()->where('id', $id)->get(); // get trashed item
return $post;
});
// read (soft) delete items *Must be using 'SoftDeletes' in Model
Route::get('/readsoftdelete', function() {
$post = Post::onlyTrashed()->get(); // get list of trashed items
return $post;
});
// restore (soft) deleted item *Must be using 'SoftDeletes' in Model
Route::get('/restore/{id}', function($id) {
$post = Post::withTrashed()->where('id', $id)->restore();
return "Record with ID #$id was restored";
});