Laravel: Error while import excel into database - excel

I am trying to export/import Excel files from/to the database. For that, I have viewed few tutorials. All show the same way for it. Here are the links.
https://www.laravelcode.com/post/laravel-8-excel-and-csv-import-export-to-database-using-maatwebsite-excel-with-example
https://www.itsolutionstuff.com/post/laravel-8-import-export-excel-and-csv-file-tutorialexample.html
And some other.
Exporting excel from the database is working fine. I am getting errors only while importing.
In both tutorials, they showed same way of importing code as shown below
public function model(array $row) {
return new product([
'vendor_id' => $row[0],
'product_name' => $row[1],
'product_price' => $row[2],
'product_model' => $row[3],
'created_at' => $row[4],
'updated_at' => $row[5],
]);
}
It is giving me this error while I am trying to import excel.
Add [vendor_id] to fillable property to allow mass assignment on [App\Models\product].
I try to search about fillable and found some solutions. I tried to apply on it but the error isn't getting resolved. Any idea where I went wrong?
UPDATE
Product Model file code
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class product extends Model {
use HasFactory;
}

You will need to specify either a fillable or guarded property on your model class. These properties are required because all Eloquent models are protected against mass assignment vulnerabilities by default.
A mass assignment vulnerability occurs when a user passes an unexpected HTTP request field and that field changes a column in your database that you did not expect. For example, a malicious user might send an is_admin parameter through an HTTP request, which is then passed to your model's create method, allowing the user to escalate themselves to an administrator.
If you are not specifying $guarded property then all fields need to be mentioned in $fillable property.
protected $fillable = ['vendor_id',
'product_name',
'product_price',
'product_model',
];
or
protected $guarded=['id']
Ref:https://laravel.com/docs/8.x/eloquent#mass-assignment

Related

Cartalyst Sentinel user registration with custom fields (solved)

Good evening.
I added a boolean field "privacy_ok" to my user model and migration.
migration file
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name',100)->nullable();
$table->string('last_name',100)->nullable();
$table->string('email');
$table->string('password');
$table->boolean('privacy_ok')->default(0);
$table->text('permissions')->nullable();
$table->timestamp('last_login')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
$table->unique('email');
});
App\User.php
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'first_name','last_name','email', 'password', 'privacy_ok'
];
....
When I try to register my user, the new field is skipped.
$user = Sentinel::register($request->all());
I noticed that, if I cause an error (a duplicate email address... for example), the INSERT query does show the "privacy_ok" field.
Is there a way to solve that?
Do I have to user User::create and than "convert" it into a Cartalyst Sentinel object to go on with all the other operations (such as activation, for example) ?
Thanks
EDIT
I found some info here
Laravel Cartalyst Sentinel - Adding a username column to users table (What is the right way)
Now I have a new file App\Models\Cartalyst\User.php, but when I add it to the cartalyst config file ( config/cartalyst.sentinel.php ), I receive an error.
'users' => [
// 'model' => 'Cartalyst\Sentinel\Users\EloquentUser',
'model' => 'App\Models\Cartalyst\User',
],
Cannot declare class User, because the name is already in use
Of course the user is there even if I change User to Lorem. It's not a naming issue.
SOLVED
I forgot to declare the namespace in the header of the new class! :(

Can't access unique identifier for Bixby using code from docs

To access a unique identifier for Bixby, I'm trying to access the contactId field within the contact library (which is also viv.self I think?). I tried using the code snippet found in the docs here, but I'm getting some errors.
Code Snippet (Source)
text (Name) {
extends (contact.StructuredName)
}
Errors
ERROR: invalid capsule alias contact
ERROR: unknown super-type: contact.contactId
I would ultimately like to do something like this
integer (Identifier) {
extends (contact.ContactId)
}
Would appreciate any help on accessing this data!
I ended up finding another way to get a device identifier from these docs. There's also a sample capsule here.
In your corresponding JavaScript file, access the $vivContext.locale parameter to return the locale information.
module.exports.function = function accessVivContext (dummyInput, $vivContext) {
var result = "Testing Access vivContext..."
// See docs for all the properties of $vivContext
result = $vivContext.userId
return result
}
You would then need to configure your endpoints for this action like below, including making sure that you set up the proper accepted-inputs for your endpoint:
action-endpoint (AccessVivContext) {
accepted-inputs (dummyInput, $vivContext)
local-endpoint ("AccessVivContext.js")
}

laravel pagination Method links does not exist

I am building a dynamic query using eloquent based on user inputs.
$query = \App\Model::query();
if($this == request('that')){
$query->where(...); // building dynamic query based on user inputs
}
and finally user can type number of records shown per page in an html input field named count or checking a checkbox input type named all and following code completes dynamic query in back-end:
if (request('all')) {
$result = $query->get();
}else {
$result = $query->paginate(request('count'));
}
Also in front-end I have following code to show pagination links:
{{$result->links()}}
The problem is when user chooses to show all records we face following error:
Method links does not exist.
links method is not callable when we retrieve objects via get() method. What is the best practice in order not to face this error?
It's because ->get() method return collection instead of paginator model Illuminate\Pagination\LengthAwarePaginator. So I can recomment you send some addition variable from your controller which indicate if you need execute $result->links().
Controller:
return view('yourView', [showPagination => is_null(request('all'))]);
View:
#if($showPagination)
{{$result->links()}}
#endif

MitreID Connect : Retrieve LDAP operational attributes

I'm working on the LDAP overlay of MitreID Connect project and everthing is working greatly:
Authentication
Retrieving attributes from LDAP Directory
The problem I have now, is how to retrieve operational attributes in LDAP directory.
I'm not good with Spring development, but I found some documentation which treat this sub, but I'm not able to make it work.
Here's what I found:
Retrieving operational attributes
Ldap Server maintains many operational attributes internally. Example entryUUID is an operational attribute assigns the Universally Unique Identifier (UUID) to the entry. The createTimestamp, modifyTimestamp are also operational attributes assigned to the entry on create or update. These operational attributes does not belong to an object class and hence they were not returned as part of your search or lookup. You need to explicitly request them by their name in your search or build the custom AttributeMapper implementation with matching attribute names.
Now let’s try to retrieve the entryUUID, first you need to build the search controls like this,
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setReturningObjFlag(false);
controls.setReturningAttributes(new String[]{"entryUUID"});
Once you have search control then it’s simply calling search method just like retrieving any other attributes.
ldapTemplate.search("baseName", "(objectclass=person)", controls, new AttributesMapper() {
public Object mapFromAttributes(Attributes attrs) throws NamingException {
Attribute attrUuid = attrs.get("entryUUID");
return attrUuid;
}});
Here is another way to do the same using ContextMapper,
ldapTemplate.search("baseName","(objectclass=person)", 1, new String[]{"entryUUID"},
new ContextMapper(){
public Object mapFromContext(Object ctx) {
DirContextAdapter context = (DirContextAdapter)ctx;
return context.getStringAttributes("entryUUID");
}
});
Let’s add the filter based off of operational attributes like below,
OrFilter orFilter = new OrFilter();
orFilter.or(new GreaterThanOrEqualsFilter("createTimestamp", "YYYYMMDDHHMMSSZ"));
orFilter.or(new LessThanOrEqualsFilter("modifyTimestamp", "YYYYMMDDHHMMSSZ"));
Now call the above search with the filter
ldapTemplate.search("baseName", orFilter.encode(), controls, new AttributesMapper() {
public Object mapFromAttributes(Attributes attrs) throws NamingException {
Attribute attrUuid = attrs.get("entryUUID");
return attrUuid;
}});

Filtering navigation property in eager loading

I have been working with soft delete and now i want to load the navigation properties of my entity that are not "deleted". I have found a way, my problem this way is not to clear for me, there is another way to do this.
Context.CreateSet().Include("Salary").Select(u => new {User= u, Salary = u.Salarys.Where(s => !s.Deleted)}).AsQueryable().Select(a => a.User).AsQueryable();
Eager loading doesn't support filtering. Your code can be simplified to:
var users = Context.CreateSet<User>()
.Select(u => new {
User = u,
Salary = u.Salaries.Where(s => !s.Deleted)
})
.AsEnumerable()
.Select(a => a.User);
Include is not needed because you are replacing it with your own query and AsQueryable is not needed because the query is IQueryable all the time till called AsEnumerable which will sqitch to Linq-to-Objects when selecting users and selected salaries. EF will take care of correctly fixing navigation properties for you.

Resources