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.
Related
OK so my User models uses webpatser/laravel-uuid. All migrations are using UUID.
So now my model looks like:
<?php
namespace App\Models;
use App\Models\Traits\Uuid;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
class User extends Authenticatable
{
use Notifiable;
use Uuid;
public $incrementing = false;
public $timestamps = true;
protected $guarded = [
'uuid',
];
protected $keyType = 'string';
protected $primaryKey = 'uuid';
protected $table = 'users';
protected $dates = [
'created_at',
'updated_at',
];
protected $hidden = [
'password',
'remember_token',
];
public function setPasswordAttribute($password): void
{
$this->attributes['password'] = Hash::make($password);
}
}
I want to use database session driver. I created session table via php artisan session:table. All migrations are done. I obviously had to rename existing user_id column. I've changed it to user_uuid. I know it's not enough as I can't find the logic responsible for populating this db table. I guess it's somewhere in the vendor (Illuminate).
Where is the logic to populate my non-default session column?
Now each open the page gives:
So I know what's the issue, what's causing it, how to change it, but I don't know where to start. Thanks for any hints.
I think you would benefit of a custom session handler because the name of the column user_id is hardcoded into the addUserInformation() method.
Extend the existing DatabaseSessionHandler.php and replace the addUserInformation() method so it looks for the correct column name:
class DatabaseUuidSessionHandler extends DatabaseSessionHandler
{
protected function addUserInformation(&$payload)
{
if ($this->container->bound(Guard::class)) {
$payload['user_uuid'] = $this->userId();
}
return $this;
}
}
Register it in one of your service providers:
class SessionServiceProvider extends ServiceProvider
{
public function boot()
{
Session::extend('databaseUuid', function ($app) {
return new DatabaseUuidSessionHandler;
});
}
}
Finally update SESSION_DRIVER in your .env to use the newly created databaseUuid driver.
Remember that this is untested code and should only be used as a guideline of how this could work.
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);
I'm currently having some troubles in testing a function in Laravel. This function is a simple save user function.
The current structure involves a User
class User extends Authenticatable
Then I have a UserController
class UserController extends Controller
{
protected $user;
public function __construct(User $user)
{
$this->user = $user;
$this->middleware('admins');
}
The save function is defined on the UserController class, this class only assigns the request variables and uses Eloquent save function to save to database.
The function signature is the following:
public function storeUser($request)
{
$this->user->name = $request->name;
$this->user->email = $request->email;
$this->user->country_id = $request->country_id;
return $this->user->save();
}
The NewAccountRequest object extends from Request and has the validation rules for the request.
class NewAccountRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:user',
'password' => 'required|min:6|max:60',
];
}
}
My problem is how can I unit test this storeUser function.
I have the current test:
public function testSaveUserWithEmptyRequest()
{
$user = $this->createMock(User::class);
$controller = new UserController($user);
$request = $this->createMock(NewAccountRequest::class);
$store = $controller->storeUser($request);
$this->assertFalse($store);
}
I'm mocking both User and NewAccountRequest, the problem is that the assertion should be false, from the Eloquent save. Instead I'm getting Null. Any idea on how can I correctly test the function?
<?php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
use DatabaseTransactions; // Laravel will automatically roll back changes that happens in every test
public function testSaveUserWithEmptyRequest()
{
$user = new User();
$controller = new UserController($user);
$request = $this->createMock(NewAccountRequest::class);
$store = $controller->storeUser($request);
$this->assertFalse($store);
}
}
This is exactly what you are trying to do, but unfortunately this will fail due to database exceptions...
Mocking a request or even manually crafting it will not do the data input validation.. and in your example password field is not nullable and will cause PDOException: SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value
The recommended way to test functions depending on request, is to use http test helpers provided by laravel like $response = $this->post('/user', ['name' => 'Sally']);
A much better approach is to use the repository design pattern.. this simply means collate your database functions into separate classes and call it from controllers ..
I've followed Jeffrey Way's explanation and several other blog posts and articles, yet still cannot get this to work.
I want to use the Eloquent ORM outside of Laravel. I've included the requirements in my composer.json:
"illuminate/database": "v5.*",
"illuminate/events": "v5.*",
Then I instantiated the Capsule Manager:
$db = new Illuminate\Database\Capsule\Manager();
$db->addConnection($config['database']);
$db->setEventDispatcher(new Illuminate\Events\Dispatcher(new Illuminate\Container\Container));
$db->setAsGlobal();
$db->bootEloquent();
I've built a basic User model that extends the Eloquent Model:
use Illuminate\Database\Eloquent\Model as Eloquent;
class User extends Eloquent
{
public $incrementing = false;
protected $primaryKey = 'username';
protected $keyType = 'string';
}
Now I can create a new User as intended:
$u = new User([
'username' => $username,
'fullname' => $fullname,
'role_id' => $role_id,
]);
$u->save();
And this works like a charm, the user appears in the intended users table fine, yet I can't retrieve a user by any of these methods, my response is always null:
$user = User::find('foo'); // no dice
$user = User::where('username', 'foo')->get(); // nope
$user = User::first(); // nothing
Does anyone know why I can't use the static methods that come with Eloquent models? Or better yet, how to fix this?
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.