Laravel mass-assignment doesnt insert boolean - php

I am trying to do the mass assignment with laravel like. But I have a field called 'hidden' that in the database is a TINYINT. From my front-end I get a boolean back. When I mass-assign with 'hidden' => TRUE the field in DB still is 0. When i convert it back to a integer ('hidden' => 1) then the field is saved as 1.
I did added 'hidden' to my $fillable.
P.S. When I try inserting it into DB directy with mysql with boolean value, it works.
Anyone know what is wrong?
EDIT: this is my code,
public function store(Request $request) {
class Group extends Model
{
use Notifiable;
const CREATED_AT = 'created';
const UPDATED_AT = 'updated';
protected $table = 'groups';
protected $casts = [
'hidden' => 'boolean',
];
protected $fillable = [
'hidden',
// etc
];
}
public function store(Request $request) {
$post = $request->all();
$group_id = Group::create($post);
}
Front-end is Vue project. So laravel is my API. And I do get a TRUE out of $post['hidden'].

You need to cast the boolean in the model:
class YourModel extends Model
{
protected $casts = [
'hidden' => 'boolean',
];
}
This will tell Laravel the you want the hidden column to be treated as boolean and values like 0 and 1 will be returned as true/false and true/false saved as 0/1.
You can read more in Laravel doc mutators.

Change the database type to Bool. If you want to do that with a migration you can do: $table->boolean(‘hidden’);

Related

laravel: Eloquent all() data is missing when converted to json

Part of data can not be acquired when Eloquent object is set to Json.
I use command artisan make:Auth, and customized users table.
Specifically, I thought that I did not need to delete the email column once,but since it became necessary, I added it again.
These operations use a migration file.
I got all the data of users table and returned it with Json.
But email is not output.
class UserController extends Controller
{
public function index() {
return User::all();
}
}
Even using json_encode did the same thing.
It exists when use this
$user = User::all();
$userArray = array();
foreach ($user as $u){
$userArray[] = [
'name' => $u->name,
'email' => $u->email
];
}
return $userArray;
Why is not email being outputted?
(I rely on google translation)
Additional notes
Thanks to everyone for comment.
Comparing the output of json with dd(), password and remember_token were not output in addition to email.
Perhaps the email is private property, and private property is a mechanism that does not output JSON?
In that case, how can I change to public?
The User model looks like this
class User extends Authenticatable
{
use Notifiable;
use SoftDeletes;
protected $table = 'users';
protected $dates = ['deleted_at'];
protected $primaryKey = 'uuid';
protected $keyType = 'string';
public $incrementing = false;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'email','remember_token',
];
~~~
}
I solved it myself.
I found that the column set here is not output to JSON.
protected $hidden = [
'password', 'email','remember_token',
];
It was a very simple thing....
try this:
return User::select('name', 'email')->get()->toArray();

Eloquent: guard ID when inserting into one database but don't guard it for another database.

I need to guard the ID column when inserting into a database, however I don't want to guard it when inserting into a different database due to needing to manually set the ID, so that the tables are in sync.
However I can't figure out a way to do it, below is what I have got at the moment, however this doesn't work at all as I just get an error:
Field 'id' doesn't have a default value
This is my current model:
<?php
namespace App\Models\Seasonal;
use Illuminate\Database\Eloquent\Model;
class SeasonalBanner extends Model
{
protected $connection = 'dev';
protected $guarded = [ 'id' ];
protected $appends = [ 'period' ];
public static function boot()
{
parent::boot();
self::creating(function($model){
if ($model->connection === 'live') {
$model->guarded = [];
}
});
}
public function dates() {
return $this->hasMany(SeasonalBannerDates::class);
}
public function getPeriodAttribute() {
return [ $this->start, $this->end ];
}
}
The best way in my opinion is not to use $guarded at all in such case. Just set:
protected $guarded = [];
and in your code depending on which database you use, either fill id or not.

Laravel 5.5: Getting id after insert

I have a model hotel.php to insert hotel data.insert data using create() but it dosen't return id, the returning collection hasn't id field!
Controller.php
/** "/user/2/create" */
public function store(User $user, HotelRequest $request)
{
$slug = (new hotel)->uniqueSlug( $request->name );
$request->merge([
'cat_id' => 1,
'slug' => $slug,
'created_by' => auth()->user()->id,
]);
$hotel = $user->hotels()->create( $request->all() );
dd($hotel);
................
hotel.php (model)
namespace App;
use Illuminate\Http\UploadedFile;
use Illuminate\Database\Eloquent\Model;
class hotel extends Model
{
protected $fillable = ['name', 'description','address','street','city','email',
'phone','web','cat_id','slug','created_by'];
protected $primaryKey = 'slug';
/**
unique slugs genarating
*/
protected $slug_guards = ['create','room'];
public $incrementing = false;
User.php (model)
public function hotels( )
{
return $this->hasmany('App\Hotel');
}
and the final result
It dosen't have id attribute. I need id to upload image!
NB: I changed that primarykey to default 'id' but no change in result.
Create_hotels... migration
public function up()
{
Schema::create('hotels', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->integer('created_by');
$table->integer('cat_id');
$table->string('name');
Your hotel model set the primary key as the slug :
protected $primaryKey = 'slug';
What i usually do, is for all my migrations, i set an autoincrements like following :
$table->increments('id');
this way laravel handles everything for you. Each create, update or whatever method handle the id of your items.
With this, you can then return the id of a stored data this way :
$id = create($data)->id;
where $data is your model with new datas. $id should now contain the id value of the newest stored model datas.
You have to change the Hotel model (or remove the whole line):
public $incrementing = true;
You are dumping the data you just inserted into the db which does not contain a id field.
create a show method in your Controller class as follows
public function show(User $user){
dd($user)
}
with a route as follows:
Route::get('user/{user}', 'Controller#show')
In hotel.php before the protected $fillable declaration try adding
protected $guarded = [
'id',
];
In your controllers store() method just after $slug = (new hotel)->uniqueSlug( $request->name );
try adding a $slug->save(); then returned slug should have an ID returned with it.
and/or possible the same similar strategy after line
$hotel = $user->hotels()->create( $request->all() );
by adding $hotel->save();
I changed the primarykey to default id and $incrementing = true; now its returning id of the created data. I changed whole methodes in Controller

Laravel 4.2 Eloquent event on select?

Is there a way to add an event on select/get with eloquent ?
I only see these methods :
public function getObservableEvents()
{
return array_merge(
array(
'creating', 'created', 'updating', 'updated',
'deleting', 'deleted', 'saving', 'saved',
'restoring', 'restored',
),
$this->observables
);
}
I want to be able to change values returned by a model
I have this model :
class Fee extends Eloquent {
protected $table = 'fees';
protected $fillable = array('occ_paxs_id',
'description',
'amount',
'other',
'hstgst',
'pst',);
}
$fee = Fee::find($id); // here I want to be able to add a markup on the property amount
Eloquent supports custom accessors and mutators. From the vague description in your question, these will likely do what you need.
class Fee extends Eloquent
{
protected $fillable = [
'occ_paxs_id',
'description',
'amount',
'other',
'hstgst',
'pst',
];
protected $appends = [
'formatted_amount',
];
/**
* Override the default attribute accessor.
*/
public function getAmountAttribute($value)
{
return "This is the amount - {$value}";
}
/**
* Or define a custom attribute accessor.
*/
public function getFormattedAmountAttribute()
{
return "This is my formatted amount - {$this->amount}";
}
}
$fee = Fee::find($id);
echo $fee->amount; // This is the amount - 0.00
echo $fee->formatted_amount; // This is my formatted amount - 0.00
You can have Observers # ORM (e.g. Fee) but it only tracks the regular operations over a single ORM instance: created, creating, updated, updating, deleted, deleting and a couple more I believe.
You can use Mutator and Accessor like this to alter data before insertion and after retrieving data:
class Fee extends Eloquent {
protected $table = 'fees';
protected $fillable = array('occ_paxs_id',
'description',
'amount',
'other',
'hstgst',
'pst',);
//Mutator = before it inserts into the database, it converts $value to a lower case string
public function setAmountAttribute($value) {
$this->attributes['first_name'] = strtolower($value);
}
//Accessor - after it retrieves data from the database, it places the capital letter in UpperCase (ucfirst).
public function getAmountAttribute($value) {
return ucfirst($value);
}
}
By creating a function that starts with get and ends with Attribute, laravel finds the attribute related based on the name. You can also get non-existant attributes and apply logic to it, if needed (for example, getting a fullName of a person in the example below, meaning a variable called fullName will be returned in your ORM result with it's content):
public function getFullNameAttribute() {
return $this->attributes['first_name'] " . " $this->attributes['last_name'];
}
https://laravel.com/docs/4.2/eloquent#accessors-and-mutators
There is a retrieved event that was added in Laravel 5.5.
The retrieved event will fire when an existing model is retrieved from the database.
https://laravel.com/docs/5.5/eloquent#events

Laravel 4.2 Eloquent create: Array to string conversion error

I'm using Laravel 4.2.* I have a User Model where insert() method is working normally but when I'm using create() method it is throwing an error:
Array to string conversion
My model:
class User extends Eloquent{
public $table = 'users';
protected $primaryKey = 'user_id';
protected $fillable = ['first_name', 'last_name', 'created_by'];
public function insertUserInfo($data)
{
//return self::insert($data); //working with no error but not adding `created_at`
return self::create($data); //Array to string conversion
}
}
Sample data:
$data = [
'first_name' => 'Jhon',
'last_name' => 'Doe',
'created_by' => Auth::id() // var_dump(Auth::id()) => int(11)
];
It 'll be helpful if anyone can help me as why create() is throwing an error.
PHP v5.6.3
EDITED
I can assure that there is no array value inside $data. and the same $data is working with insert() but throwing error when using create() or save() method.
Add array type hinting:
public function insertUserInfo(array $data)
{
return self::create($data);
}

Categories