Git Product home page Git Product logo

cb-model's Introduction

CB Laravel Model Repository

An alternative about laravel eloquent

This Package Is Deprecated

Please use https://github.com/crocodic-studio/laravel-model

Requirement

Laravel 5.* | 6.* | 7.*

Install Command

composer require crocodicstudio/cbmodel=^2.0

1. Create a model

Create a model from a table
php artisan create:model foo_bar_table

Create model for all tables
php artisan create:model

Create a model with other connection
php artisan create:model foo_bar_table --connection=con2

I assume that you have a books table with the structure like bellow:

id (Integer) Primary Key
created_at (Timestamp)
name (Varchar) 255

It will auto create a new file at /app/Models/Books.php with the following file structure :

<?php
namespace App\Models;

use DB;
use Crocodicstudio\Cbmodel\Core\Model;

class Books extends Model
{
    public $tableName = "books";
    public $connection = "mysql";
    public $primary_key = "id";

    public $id;
    public $created_at;
    public $name;
}

2. Using CB Model class on your Controller

Insert use App\Models\Books; at top of your controller class name.

<?php 
namespace App\Http\Controllers;

use App\Models\Books;

class FooController extends Controller {
    
    public function index() 
    {
        $books = Books::latest();
        return view("books", ["bookData"=>$books]);
    }
    
    public function detail($id)
    {
        $book = Books::find($id);
        return view("book_detail", ["book"=>$book]);
    }
    
    public function delete($id)
    {
        Books::deleteById($id);
        
        return redirect()->back()->with(["message"=>"Book ".$book->name." has been deleted!"]);
    }
}
?>

3. Using CB Model class that has a relation

I assume you have a table categories for book relation like bellow :

id (Integer) Primary Key
name (Varchar) 255

and your book structure to be like bellow:

id (Integer) Primary Key
created_at (Timestamp)
categories_id (Integer)
name (Varchar) 255

Now you have to create a model for categories table, you can following previous steps.

I assume that you have create a categories model, so make sure that now we have two files in the /app/Models/

/Books.php
/Categories.php

Open the Books model , and add this bellow method

    /**
    * @return Categories
    */
    public function category() {
        return $this->belongsTo("App\Models\Categories");
    }

    // or 
    /**
    * @return Categories
    */
    public function category() {
        return Categories::find($this->categories_id);
    }

Then open the FooController

<?php 
namespace App\Http\Controllers;

use App\Models\Books;

class FooController extends Controller {
    
    ...
    
    public function detail($id)
    {
        $book = Books::find($id);
        
        $data = [];
        $data['book_id'] = $book->id;
        $data['book_name'] = $book->name;
        $data['book_category_id'] = $book->category()->id;
        $data['book_category_name'] = $book->category()->name;
        
        return view("book_detail",$data);
    }
    
}
?>

As you can see now we can get the category name by using ->category()->name without any SQL Query or even Database Builder syntax. Also you can recursively go down to your relation with NO LIMIT.

4. How to Casting DB Builder Collection output to CB Model Class?

You can easily cast your simple database builder collection to cb model class.

$row = DB::table("books")->where("id",1)->first();

//Cast to CB Model
$model = new Books($row);

//And then you can use cb model normally
echo $model->name;

5. How to insert the data with CB Model

You can easily insert the data with method ->save() like bellow:

$book = new Books();
$book->created_at = date("Y-m-d H:i:s"); //this created_at is a magic method you can ignore this
$book->name = "New Book";
$book->categories_id = 1;
$book->save();

Then if you want to get the last insert id you can do like bellow:

...
$book->save();
$lastInsertId = $book->id; // get the id from id property
...

5. How to update the data with CB Model

You can easily update the data, just find it for first :

$book = Books::findById(1);
$book->name = "New Book";
$book->categories_id = 1;
$book->save();

5. How to delete the data?

You can easily delete the data, just find it for first :

$book = Books::findById(1);
$book->delete();

or

Books::deleteById(1);

Model Method Available

/**
* Find all data by specific condition.
*/ 
$result = FooBar::findAllBy($column, $value = null, $sorting_column = "id", $sorting_dir = "desc");
// or 
$result = FooBar::findAllBy(['foo'=>1,'bar'=>2]);

/**
* Find all data without sorting
*/
$result = FooBar::findAll();

/**
* Count the records of table
*/ 
$result = FooBar::count();

/**
* Count the records with specific condition 
*/
$result = FooBar::countBy($column, $value = null);
// or
$result = FooBar::countBy(['foo'=>1,'bar'=>2]);

/**
* Find all datas and ordering the data to descending
*/
$result = FooBar::findAllDesc($column = "id");
// or simply
$result = FooBar::latest();

/**
* Find all datas and ordering the data to ascending
*/
$result = FooBar::findAllAsc($column = "id");
// or simply
$result = FooBar::oldest();

/** 
* Find/Fetch a record by a primary key value
*/
$result = FooBar::findById($id);
// or simply
$result = FooBar::find($id);

/**
* Create a custom query, and result laravel Query Builder collection
*/
$result = FooBar::table()->where("foo",1)->first();

/**
* Create a custom query and casting to model object
*/
$result = FooBar::query(function($query) {
    return $query->where("bar",1);
});

/**
* Create a custom list query and casting them to model objects
*/
$result = FooBar::queryList(function($query) {
    return $query->where("bar",1);
});


/**
* Find a record by a specific condition
*/
$result = Foobar::findBy($column, $value = null);
// or 
$result = Foobar::findBy(['foo'=>1,'bar'=>2]);

/**
* To run the insert SQL Query
*/
$fooBar = new FooBar();
$fooBar->name = "Lorem ipsum";
$fooBar->save();

/**
* To bulk insert
*/
$data = [];
$foo = new FooBar();
$foo->name = "Lorem ipsum 1";
array_push($data, $foo);
$bar = new FooBar();
$bar->name = "Lorem ipsum 2";
array_push($data, $bar);
FooBar::bulkInsert($data);


/**
* To run the update SQL Query
*/
$fooBar = FooBar::findById($value);
$fooBar->name = "Lorem ipsum";
$fooBar->save();

/**
* To delete the record by a primary key value
*/
FooBar::deleteById($value);

/**
* To delete the record by a specific condition
*/
FooBar::deleteBy($column, $value = null);
// or
Foobar::deleteBy(['foo'=>1,'bar'=>2]);

/**
* To delete after you fetch the record 
*/
$fooBar = FooBar::findById($value);
$fooBar->delete();

A One-To-Many Relationship

class Posts extends Model {
    // etc
    
    /**
    * @return App\Models\Comments[]
    */
    public function comments() {
        return $this->hasMany(Comments::class);
    }
    
    // or with full option
    /**
    * @return App\Models\Comments[]
    */
    public function comments() {
        return $this->hasMany(Comments::class, "foreign_key", "local_key", function($condition) {
            return $condition->where("status","Active");
        });
    }
}

A One-To-One Relationship

class Comments extends Model {
    // etc
    
    /**
    * @return App\Models\Posts
    */
    public function post() {
        return $this->belongsTo(Posts::class);
    }
    
    // or with full option
    /**
    * @return App\Models\Posts
    */
    public function post() {
        return $this->belongsTo(Posts::class, "foreign_key", "local_key");
    }
}

Other Useful

  1. CRUDBooster Laravel CRUD Generator

cb-model's People

Contributors

fherryfherry avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

dsyman2

cb-model's Issues

Modular/Package Structure

When looking into CrudBooster, I became interested in it because it seemed to understand the kind of modular/package architecture that are essential to virtually ever modern web application. You can imagine my horror when I discovered that your cb-model package simply slings all models into a non-standard directory called app\CBModels. Horrors!!!!!!!!!!!!!!!!!! My application, which is not fully developed at this time has 217 tables most of which have at least three or four relationships to other tables.. Do you expect me to sling, willy-nilly, 217++++ models into one directory? How would I ever manage that?

Do you have any plans to incorporate module support into this package? I tried making the models for my smallest, almost trivial module. (I'm currently using nwidart/laravel-modules for my modular architecture. It's great.You should build CrudBooster and CB-Models to accommodate such packages.) Anyway, this smallest of my 26 modules has five tables and models in it. I can't believe that your package would dump these models in the same directory with over twenty entirely unrelated modules and their models. This application that I'm working on is very much like the complexity of what my colleagues are developing, although it is somewhat smaller than theirs.

Do you plan to develop this CBModel package into a mature, workable package? If so, when? I'm working on my application right now and hope to push it into production status in the next month or two. If not, will CrudBooster work with any models that conform to Laravel specifications?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.