Database Eloquent ORM Soft Deleting / Trashing

Update your model to include soft deletes like this:

use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;
    protected $dates = ['deleted_at'];

}

Now create a migration (name of file with flag for name of database table to add onto)

php artisan make:migration add_deleted_at_column_to_posts_tables --table=posts

Now add your new columns to this file in the up and down functions like so:

    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->softDeletes();
        });
    }


    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('deleted_at');
        });
    }

Get the new column to show up with:

php artisan migrate

To your routes file add this to soft delete an item in the database:

Route::get('/softdelete', function(){
    Post::find(11)->delete();
});

Now running queries like Post::all() won’t find the soft deleted items anymore so check the database directly.

Database Eloquent ORM Deleting

Multiple ways of deleting:

use App\Models\Post;

/*
|--------------------------------------------------------------------------
| ELOQUENT ORM (Object Relational Model)
|--------------------------------------------------------------------------
*/

Route::get('/delete', function(){
    $post = Post::find(2);
    $post->delete();
});

Route::get('/delete2', function(){
    Post::destroy(3);
});

Route::get('/delete3', function(){
    Post::destroy([4,5]);
});

Route::get('/delete4', function(){
    Post::where('is_admin',0)->delete();
});

Database Eloquent ORM Updating

use App\Models\Post;

/*
|--------------------------------------------------------------------------
| ELOQUENT ORM (Object Relational Model)
|--------------------------------------------------------------------------
*/

Route::get('/update', function(){
    Post::where('id',2)->where('is_admin',0)->update(['title'=>'NEW PHP TITLE','content'=>'More content']);
});

Second way of updating. First way uses same method as inserting.

Database Eloquent ORM Creating data and configuring mass assignment

First add a create method:

use App\Models\Post;

/*
|--------------------------------------------------------------------------
| ELOQUENT ORM (Object Relational Model)
|--------------------------------------------------------------------------
*/

Route::get('/create', function(){
    Post::create(['title'=>'the create method', 'content'=>'learning about create method']);
});

Now check URL. You should get an error like so:

Add [title] to fillable property to allow mass assignment on [App\Models\Post].

To allow us to save multiple items of data you need to edit your model with this inside the class:

protected $fillable = [
    'title',
    'content'
];

If you check the URL again you should get an error free page and if you check phpmyadmin, you’ll see a new record.

Database Eloquent ORM Inserting / Saving Data

use App\Models\Post;

/*
|--------------------------------------------------------------------------
| ELOQUENT ORM (Object Relational Model)
|--------------------------------------------------------------------------
*/

Route::get('/basicinsert', function(){
    $post = new Post;
    $post->title = 'New Eloquent title insert';
    $post->content = 'Wow Eloquent is really cool';
    $post->save();
});

Route::get('/basicinsert2', function(){
    $post = Post::find(2);
    $post->title = 'New Eloquent title insert 2';
    $post->content = 'Wow Eloquent is really cool 2';
    $post->save();
});

The second one is really an update statement using find to find by ID, then updating the title and content.

Database Eloquent ORM Reading / Finding with Constraints

In your routes you can test Eloquent reading and finding statements. First include your model to reference, then write your read statements:

use App\Models\Post;

/*
|--------------------------------------------------------------------------
| ELOQUENT ORM (Object Relational Model)
|--------------------------------------------------------------------------
*/

Route::get('/all', function(){
    $posts = Post::all();
    foreach($posts as $post){
        return $post->title;
    }
});

Route::get('/find', function(){
    $post = Post::find(2);
    return $post->title;
});

Route::get('/findwhere', function(){
    $posts = Post::where('id',2)->orderBy('id','desc')->take(1)->get();
    return $posts;
});

Route::get('/findorfail', function(){
    $posts = Post::findOrFail(1);
    return $posts;
});

Route::get('/firstorfail', function(){
    $posts = Post::where('users_count','<',50)->firstOrFail;
    return $posts;
});

The find condition needs the ID of the row in database. The where condition is also looking for the ID of the row (though could look for anything).

Defining a Model Laravel

Models connect to your database. Model is always a singular name, while the database table is the plural name of the model. See example below

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
}

This model is named Post which means it automatically will look for a database table named “posts” in lowercase. The default ID it will look for will be named “id”.

You can change the defaults of the table name and id name like this:

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    protected $table = 'posts_table';
    protected $primaryKey = 'post_id';
}

Raw SQL Queries in Laravel

Add these to your routes to see raw SQL working:

Route::get('/insert', function () {
    DB::insert('insert into posts(title, content) values(?,?)',['PHP with Laravel', 'Laravel is the best thing that has happened to PHP']);
});

Route::get('/read', function () {
    $results = DB::select('select * from posts where id=?',[1]);
    foreach($results as $post){
        return $post->title;
    }
});

Route::get('/update', function () {     
    $updated = DB::update('update posts set title="Update title" where id=?',[1]);
    return $updated;
});  

Route::get('/delete', function () {     
    $deleted = DB::delete('delete from posts where id=?',[1]);
    return $deleted;
});  

Add columns to existing tables using migrate

Creates another file name and specifies it targets already created table named “posts”:

php artisan make:migration add_is_admin_column_to_posts_table --table="posts"

Inside your up function add a new column to this table like so:

$table->integer('is_admin')->unsigned();

In your down function make sure to drop the column as well:

$table->dropColumn('is_admin');

Then add this column to database by adding this to terminal:

php artisan migrate

Check phpmyadmin to see new column