7 months ago

Query Builder and Models

Posted 7 months ago by TuffRivers

Hi All,

I am electing not ot use eloquent for this project and im new to OOP so im having a hard time understanding when i should be working with an object and when with arrays.

I am testing my web api service to create a new user but having some difficulty saving to my database. I know that if i use PDO i can create an insert statement and write my Request $request fields to an array and easily bind it and insert it in my model function insert($userOptions), but why would i then create a new model in my controller just to convert it to an array after? Can i write objects to my databse without eloquent?

Sorry for the confusion, im a noob!



namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;

class User extends Authenticatable


    use HasApiTokens, Notifiable;

    public $id;
    public $first_name;
    public $last_name;
    public $email;
    public $alerts;
    public $status;
    public $client_id;
    public $password;

    public function insert($user){

       DB::table('users')->insert($user); //this will not work because $user is an object
        return $user;



namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\User;
use Validator;
class UserController extends BaseController
     * Register api
     * @return \Illuminate\Http\Response
    public function register(Request $request)
        $validator = Validator::make($request->all(), [
            'first_name' => 'string|required',
            'last_name' => 'string|required',
            'client_id' => '',
            'email' => 'required|email',
            'password' => 'required',
            'c_password' => 'required|same:password',
            return $this->sendError('Validation Error.', $validator->errors());       

        $data = $request->only('first_name','last_name','client_id','email','password');
        $user = new User; //create a user model, whats the point if i just build it as an array and pass to my insert function ?
        $user->first_name = $data['first_name'];
        $user->last_name = $data['last_name'];
        $user->client_id = $data['client_id'];
        $user->email = $data['email'];
        $user->password = bcrypt($data['password']);

        $user->insert($user); //call insert function in my model passing the user 
        return $this->sendResponse($user, 'User created.');

Please sign in or create an account to participate in this conversation.