We are having a strange issue with Laravel 5 in that it is refusing to store the checkbox value.
We are adapting the existing registration form that comes bundled with Laravel 5 and we are adding an optin checkbox but it seems the model does not recognise this as a field even though we are adding it as a field in the migration file.
Any help on this would be appreciated.
Mirgration File:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('password', 60);
$table->date('dob');
$table->boolean('optin')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
Then we add it to the register.blade.php file:
<div class="form-group">
<label class="col-md-4 control-label">Optin</label>
<div class="col-md-6">
<input type="checkbox" class="form-control" name="optin">
</div>
</div>
At the point of creating the User model, we check the value of the checkbox and assign it.
protected function create(array $data)
{
//this does return 1 or 0 as expected
$optin = ($data["optin"] == "on") ? 1 : 0;
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'dob' => $data['dob'],
'optin' => $optin
]);
}
But at this point the field is null. No value is entered into the database...
Have you put the field 'optin' in the $fillable array within the model? Otherwise you cant create a User with 'optin' using the static create method.
//File: User.php
protected $fillable = ['optin'];
The model already has a static create() function. Therefore, when you make a call like User::create($data) from your controller, your function is not called.
My approach is to change the name of your function and make it static.
Update
Also you can override the create function:
public static function create(array $attributes)
{
$attributes["optin"] = ($attributes["optin"] == "on") ? 1 : 0;
return parent::create($attributes);
}
Related
This is my original table called questions:
public function up()
{
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('slug');
$table->string('image')->nullable();
$table->string('audio')->nullable();
$table->string('type');
$table->unsignedBigInteger('evaluation_id');
$table->foreign('evaluation_id')->references('id')->on('evaluations')->onDelete('cascade');
$table->timestamps();
});
}
And with this code, I added a new column to the existing table:
php artisan make:migration add_rule_to_questions_table --table=questions
php artisan migrate
In the migration file of the new column added this in up() method:
public function up()
{
Schema::table('questions', function (Blueprint $table) {
$table->longText('rule')->nullable();
});
}
At this point, the new column added succesfully to the database. But, when I try to add data to the new column of the "questions" table, data is not saved in the database.
In create form I use this code:
<div class="form-group">
<label>Rules:</label>
<textarea name="rule" id="rule" class="form-control" value="{{old('rule')}}"></textarea>
#error('rule')
<small class="text-danger">{{$message}}</small>
#enderror
</div>
Finally in store method() of controller I save data with this code:
public function store(Request $request){
Question::create([
'title' => $request->title,
'slug' => $request->slug,
'evaluation_id' => $request->evaluation_id,
'type' => "OM",
'rules' => $request->rule,
]);
}
But the new column is not saving data, what could be the error?
You need add rules to array $fillable in your Question model
In my database i have this
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique();
$table->string('admin')->nullable();
$table->string('usertype')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Which means in my form i have this
<select name="usertype">
<option>Select Usertype</option>
<option value="1">Landlord</option>
<option value="2">Agent</option>
<option value="3">Tenant</option>
</select>
Users can select the type of user they are.
I have this in my RegisterController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'username' => $data['username'],
'usertype' => $data['usertype'],
'password' => Hash::make($data['password']),
]);
}
When a user which is landlord registers it takes them to http://127.0.0.1:8000/dashboard
How can i make the content different for each users i.e
1. I want landlord to be able to just add property
2. I want tenant to be able to edit profile, see properties they have bought.
3. I want agent to able to add property like landlord.
How can i achieve this ?
You can make use of Laravel Policies. Example if you have a PropertyController, you can have a PropertyPolicy with the method:
/**
* Determine whether the user can create models.
*
* #param \App\User $user
* #return mixed
*/
public function create(User $user)
{
return $user->usertype == 'Landlord';
}
And in the view, you can do something like:
#can('create', $property)
// link to create property
#endcan
learn more about Laravel Policies at https://laravel.com/docs/7.x/authorization#creating-policies
I am creating factories and saving the page model to the film model so its film to page one-to-many,
i've followed the docs but when im trying to save the models to each other i am getting this error
General error: 20 datatype mismatch (SQL: insert into "pages" ("id", "page_url", "film_id", "updated_at", "created_at") values (591d61cb-3090-3945-b920-ba797245cb97, http://larson.com/, bd3bab38-f8be-4674-ae5d-15e8f6b6172a, 2019-11-15 11:23:02, 2019-11-15 11:23:02))
These are the classes i am working with
Film migration
public function up()
{
Schema::create('films', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->string('description');
$table->timestamps();
});
}
Pages migration
public function up()
{
Schema::create('pages', function (Blueprint $table) {
$table->bigIncrements('id');
$table->uuid('film_id')->nullable();
$table->string('page_url')->nullable();
$table->timestamps();
});
}
PagesFactory
$factory->define(Pages::class, function (Faker $faker) {
return [
'id' => $faker->uuid,
'page_url' => $faker->url,
'film_id' => factory(\App\Models\Film::class)->create()->id
];
Pages model
public function film(): BelongsTo
{
return $this->belongsTo(Film::class);
}
FilmController
*/
public function show(string $id)
{
$film = Film::with([
'pages',
'languages',
'categories',
])->findOrFail($id);
return $film;
FilmControllerTest
public function getFilmTest()
{
$film = factory(Film::class)->create();
$language = Language::where('id', 'en')->where('name', 'English')->first();
$categories = Category::where('main-cat', 'Science')->where('sub-cat', 'Fiction')->first();
$film->pages()->save(factory(Page::class)->create());
$film->languages()->attach($language->id);
$film->categories()->attach($categories->id);
$response = $this->json('GET', '/film/' . $film->id)
->assertStatus(200);
$response
->assertJson(['id' => $guestProfile->id])
->assertJson(['name' => $film->description])
->assertJson(['languages' => $film->languages->toArray()])
->assertJson(['categories' => $film->categories->toArray()])
}
when i comment out this line from the test it works fine $film->pages()->save(factory(Page::class)->create());
im abit lost on why im having this issue trying to save the models so the pages becomes part of the response... can i get some help/example please :D
The id of your pages table is set to a bigIncrements (UNSIGNED BIGINT), but in your PagesFactory you are trying to store a uuid.
$factory->define(Pages::class, function (Faker $faker) {
return [
'id' => $faker->uuid,
'page_url' => $faker->url,
'film_id' => factory(\App\Models\Film::class)->create()->id
];
Remove 'id' => $faker->uuid, from the factory, you don't have to set an auto incrementing field.
Another option (depending on the design you have in mind) is to change the migration of the pages table and set the id column to $table->uuid('id')->primary();
try using the make() method, as in:
$film->pages()->save(factory(Page::class)->make());
I am trying to save boolean value when I create a new Post and then have it update the value if I update the Post. When I create a new Post and save, it persists to the database and I can even update it without issue. I am just having a little trouble dealing with a checkbox boolean. This is my fist project in Laravel, which is part of my hurdle I'm sure.
schema
...
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->text('body')->nullable();
$table->string('photo')->nullable();
$table->boolean('is_featured')->nullable()->default(false);
$table->boolean('is_place')->nullable()->default(false);
$table->string('tag')->nullable()->default(false);
$table->timestamps();
});
Schema::table('posts', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users');
});
}
...
PostController.php
...
public function store(Request $request)
{
$rules = [
'title' => ['required', 'min:3'],
'body' => ['required', 'min:5']
];
$request->validate($rules);
$user_id = Auth::id();
$post = new Post();
$post->user_id = $user_id;
$post->is_featured = request('is_featured');
$post->title = request('title');
$post->body = request('body');
$post->save();
$posts = Post::all();
return view('backend.auth.post.index', compact('posts'));
}
...
post/create.blade.php
...
<input type="checkbox" name="is_featured" class="switch-input"
value="{{old('is_featured')}}">
...
If I'm understanding the problem correctly, you can cast the attribute as a boolean in the model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $casts = [
'is_featured' => 'boolean',
'is_place' => 'boolean',
];
}
Then in your form you'll want to check that value to determine if the box is checked.
<input type="checkbox" name="is_featured" class="switch-input" value="1" {{ old('is_featured') ? 'checked="checked"' : '' }}/>
In your controller, you'll want to just check if the input is submitted. An unchecked input won't be sumitted at all.
$post->is_featured = $request->has('is_featured');
try this
$post->is_featured = $request->input('is_featured') ? true : false;
I am having trouble in laravel 5.1 registration in the AuthController the validate and create method. I make may login and register forms in one page so I added register- on the inputs of the registration form (ex. register-email for the email address in the registration form). So my validate method in the AuthController is this:
App\Auth\Http\Controllers\Auth
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'last-name' => 'required|between:2,35',
'first-name' => 'required|between:2,35',
'register-email' => 'required|email|max:255|unique:users',
'register-password' => 'required|confirmed|min:8',
'register-confirm-password' => 'same:register-password'
]);
}
The last-name, first-name, register-email, etc is a html inputs right? So I think this is right?
and then this is the create method:
protected function create(array $data)
{
return User::create([
'last-name' => $data['last-name'],
'first-name' => $data['first-name'],
'email' => $data['register-email'],
'password' => bcrypt($data['register-password'])
]);
}
The keys in the create method is the database table right? and the value is the html input name/id? I am getting Unknown column error of register-email why is that? I know I don't have register-email column in the database but, in the create method I specify the email column in the database and not register-column which is the html input name of my registration form. Please help.
BTW this is my database migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('last-name');
$table->string('first-name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}