Laravel 5.6 database operations in model - php

I have a controller called UserController, in that controller i am inserting a row of data to table "user" like this
$user = new UsersModel();
$user->first_name = $request->input('firstName');
$user->last_name = $request->input('lastName');
$user->about = $request->input('userAbout');
$user->join_date = date('Y-m-d');
$user->save();
My Question is, can i write this in my model called UsersModel???
Something Like,
( The insertData($data) is called from controller class.)
class UsersModel extends Model
{
protected $fillable = ['id','first_name','last_name','about','image','join_date','created_at','updated_at'];
protected $table = 'users';
public function insertData($data) {
// nb: $data contains values of fileds
// insert operation
//also return some values
}
}

You don't need to define your own function when you can already do it through Eloquent by simply calling the static method create magically:
$ref = UsersModel::create([
'col' => 'val'
]);
where $ref contains the information about the created data.
No need to reinvent the wheel in this instance.
However, your own custom method is possible too, make sure your function is defined as static to allow you to use without an object reference.

Yes you can
you need to call the function from the controller like this
$data = ['YOUR ARRAY'];
$this->usersModel = new UsersModel();
$this->usersModel->insertData($data);
You can also do with static function
In Model
public static function insertData($data) {
In Controller
UsersModel::insertData($data);
Insert function
UsersModel::insert($data);

Related

eloquent: How to load and set model variables, inside the model itself?

Laravel documentation suggests the following way to set up an eloquent model:
$user = user::with($conditions)->first();
What if I want to set up my eloquent model inside the model itself:
$user = new user();
$user->setup($conditions);
// class definition
class user extends Eloquent{
public function setup($conditions){
// load current object with table data
// something like
$this->where($conditions)->first();
// previous line output is dangling, is ok to assign it to $this variable?
}
}
If you're extending from Eloquent model, you may try the following approach. I assume you have a unique id column.
public function setup($conditions)
{
$model = self::with($conditions)->first();
if (! is_null($model)) {
$this->exists = true;
$this->forceFill(self::find($model->id)->toArray());
}
return $this;
}
Hope this solve your issue.

Laravel eloquent issue with constructor

I have a model which contains many methods.
class UserModel extends Eloquent{
private $active;
function __construct() {
$this->active = Config::get('app.ActiveFlag');
}
protected $table = 'User';
protected $fillable = array('usr_ID', 'username');
public function method1(){
//use $active here
}
public function method2(){
//use $active here
}
}
Controller:
$user = new UserModel($inputall);
$user->save();
Without constructor, it works fine. However, with constructor it doesn't save the user (the query which is generated doesn't have any fill attributes or values). The query is as follows:
insert into User() values();
Any inputs please?
Well yes, that's because you override the Eloquent constructor which is responsible to fill the model with values when an array is passed. You have to pass them along to the parent with parent::__construct():
public function __construct(array $attributes = array()){
parent::__construct($attributes);
$this->active = Config::get('app.ActiveFlag');
}
Your model's constructor doesn't accept any parameters - empty (), and you are creating new instance of UserModel in your controller adding $inputall as a parameter.
Try to refactor your contructor according to this:
class UserModel extends Eloquent {
public function __construct($attributes = array()) {
parent::__construct($attributes);
// Your additional code here
}
}
(Answer based on other Eloquent contructor question)

passing arguments to Model constructor

How can i pass my arguments to the model constructor,i have the following code in my controller
public static function inbox(){
$user=Sentry::getUser();
$results=new Message($user->id);
$inbox=$results->inbox();
return $inbox;
}
And in my modal i am extending the parent modal constructor as follows
class Message extends \Eloquent {
private $user_id;
public function __construct($attributes = array()) {
parent::__construct($attributes); // Eloquent
}}
now i want to pass the $user_id to the Message modal constructor,how do i achieve this
when inserting data to the db using the Eloquent create nothing is being inserted into the database here is the code
Message::create(
array(
'msg_id'=>$result->id,
'subj'=>Input::get('subj'),
'content'=>Input::get('content'),
'sender_id'=>Input::get('sender_id'),
'receivers_id'=>$user->id,
'file'=>Input::get('file')
)
);
its like i have overidden built-in constructor of the Model class
You can use #PeterPopelyshko's approach and override the constructor or just use what Eloquent offers. Mass Assignment.
You can pass in attributes through your constructor by using an associative array:
$results = new Message(array(
'user_id' => $user->id
));
Just make sure to define all the properties, you want to be fillable in the $fillable array in your model:
class Message extends \Eloquent {
protected $fillable = array('user_id');
}
Note that you don't need the private $user_id if this is a database field. Laravel handles them in it's own $attributes array.
class Message extends \Eloquent {
private $user_id;
public function __construct($user_id, $attributes = array()) {
$this->user_id = $user_id;
parent::__construct($attributes); // Eloquent
}}
and then you can use it in your controller
$results=new Message($user->id);
and you can get access to $user_id within model like this $this->user_id

Saving from eloquent constructor in laravel

So, I'm currently working on a browser game in Laravel. So far I love the framework, but I haven't really got much experience, and I just can't get this to work.
Basically I'm trying to update all users whenever they are instantieted, as there is no reason update them when they are not used. But calling this function from the constructor doesn't update the user, it only works when I call the function outside the constructor.
Have I missed anything, or is it just not possible?
Thanks in advance!
<?php
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function __construct($arguments = array())
{
parent::__construct($arguments);
$this->updateHp();
}
public function updateHp()
{
$this->hp_last = time();
$this->save();
}
}
Eloquent is a static class, data is fetched on query (find, first, get) and when you create a model you have just a blank model, with no data on it. This is, as example, the point where you have some data available:
public static function find($id, $columns = array('*'))
{
if (is_array($id) && empty($id)) return new Collection;
$instance = new static;
return $instance->newQuery()->find($id, $columns);
}
Before one of those query methods, you have void.
So you probably cannot do that during __construct because your model is still blank (all nulls). This is what you can do to make it, somehow, automatic:
First, during boot, create some creating and updating listeners:
public static function boot()
{
static::creating(function($user)
{
$user->updateHp($user);
});
static::updating(function($user)
{
$user->updateHp($user);
});
parent::boot();
}
public function updateHp()
{
$this->hp_last = time();
$this->save();
}
Then, every time you save() a model it will, before saving, fire your method:
$user = User::where('email', 'acr#antoniocarlosribeiro.com')->first();
$user->activation_code = Uuid::uuid4();
$user->save();
If you want to make it somehow automatic for all your users. You can hook it to a login event. Add this code to your global.php file:
Event::listen('user.logged.in', function($user)
{
$user->updateHp();
})
Then in your login method you'll have to:
if ($user = Auth::attempt($credentials))
{
Event::fire('user.logged.in', array($user));
}
In my opinion you shouldn't do that. If you use the code:
$user = new User();
you would like to be run:
$this->hp_last = time();
$this->save();
and what exactly should happen in this case? New user without id should be created with property hp_last ?
I think that's not the best idea.
You should leave it in the function then you can use:
$user = new User();
$user->find(1);
$user->updateHp();
That makes much more sense for me.

Laravel : add new row in model table

I have a user model defined, and I'm trying to add a new user in my database using a form, what is the best and fastest way to do it, I have read something about model forms binding but I think it's just for updating not for adding new rows.
I'm new in Laravel and couldn't find some good tutorials, I must recognize that Laravel documentation is really poor, so any links to some good and well explained tutorials are welcomed.
Thank you
Assumed that, you have a User model (app/models/User.php) the one came with Laravel by default, which may look like this:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'users';
protected $hidden = array('password');
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->password;
}
public function getReminderEmail()
{
return $this->email;
}
}
Now, from a controller (Basically) you may use somethng like this:
$user = new user;
$user->username= 'Me';
$user->email = 'me#yahoo.com';
// add more fields (all fields that users table contains without id)
$user->save();
There are other ways, for example:
$userData = array('username' => 'Me', 'email' => 'me#yahoo.com');
User::create($userData);
Or this:
User::create(Input::except('_token'));
This requires you to use a property in your User model like this:
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $fillable = array('username', 'email');
// Or this, (Read the documentation first before you use it/mass assignment)
protected $guarded = array();
}
Since, you are still new to Laravel you may use first example and read about Mass Assignment, then you may use the second one if you want.
Update:
In your controller, you may use Input::get('formfieldname') to get the submitted data, for example:
$username = Input::get($username);
So, you can use these data like this:
$user = new User;
$user->username= $username;
Or directly you can use:
$user->email = Input::get($email);
$user->save();
In the form, you have to set the form action, where you'll submit the form and in this case you have to declare a route, for example:
Route::post('user/add', array('as' => 'user.add', 'uses' => 'UserController#addUser'));
Then in your controller you have to create the method addUser, like this:
class UserController extends addUser {
// other methods
public function addUser()
{
$user = new user;
$user->username = Input::get('username');
$user->email = Input::get($email);
$user->save();
}
}
In your form you may use this:
Form::open(array('route' => 'user.add'))
Read the documentation properly, you can do it easily.

Categories