laravel mongodb does not save - php

The documentation doesn't go into much detail about saving data to mongodb.
I've installed a fresh install of laravel and set the up the mongo connections as in the docs, installed mongodb itself.
Created a model
use Jenssegers\Mongodb\Model as Eloquent;
class Notifications extends Eloquent {
protected $connection = 'mongodb';
protected $collection = 'notifications';
public static function foo()
{
return 'test returning from model';
}
}
And create a simple route to test
Route::get('notifiction' , function(){
$notifiction = new Notifications();
$arr = array('name' => 'John Doe');
$notifiction->save($arr);
});
But when I run localhost/mongo/public/notifiction I get Whoops, looks like something went wrong. I'm not sure what else needs doing to save information to mongodb through laravel?

This error is most likely to do with mass assignment. That is laravel treats every thing as unsafe before saving it to database. Thus we have to whitelist the fields we are trying to save.
The way we do this is in model. Lets say you are trying to save data in Users table using USER model. First open app/models/user.php and add following line:
class User extends Eloquent {
protected $fillable = ['name'];
}
Above, in fillable we are listing name as we want to save name from controller (if you have any additional data fill in the array). Now we can save data from controller.
Eg: User::create(array('name' => 'John')); will save name in Users collection. Please note the name of collection will be the name of the model unless specified otherwise.
[If this does not solve your problem, enable debug by going to app/config/app.php and setting debug =true. Find the error and try searching.]

You need not to do like model for SQL.
You try model like this
class User extends Moloquent {
protected $connection = 'mongodb';
protected $collection = 'collection1';
protected $fillable = ['_id','userName','passwd'];
}
You can try this to insert
DB::connection('mongodb')->collection('collection1')
->insert(array(
'_id' => 'H12345',
'userName' => 'Nithil',
'passwd' => 'qwoeuig'));
Using Moloquent is more convenient in using multiple DBS. For using Moloquent, you may register an alias for the MongoDB model by adding the following to the alias array in app/config/app.php:
'Moloquent' => 'Jenssegers\Mongodb\Model',
This will allow you to use the registered alias like:
class MyModel extends Moloquent {}

As OP has mentioned the error was due to
Did not installed the MongoDB PHP Library
Apart from that, to do mass assignment in Laravel, the fields should either be "white listed" or "black listed"
To whitelist the field(s) add
// name, age, username and email could be mass assigned
protected $fillable = ['name', 'age', 'username', 'email'];
To blacklist the field(s) add
// except _id everything could be mass assigned
protected $guarded = ['_id'];
to your model file

Related

Specific question Laravel Database Homepage

I started using Laravel few days before.
I'm actually struggling with a problem, I created a homepage and I want to replace some text of the page with content from my database.
So how do I create a model/controller, and after that I will make an admin panel, so I can edit them.
The only tutorials/docs I see are for making a form/post to create users
Example
In basic php it's easy you just do a pdo connection and then a fetch and you use your date as you want. How do you do it in laravel ?
To fetch data from the DB in Laravel can be done in 1 of two ways, 1. using a Model (the best way) or using a Query Builder, which is much more familiar to those migrating from pure PHP.
Using a Model
Create a model using php artisan make:Model (change Model with a name of your choosing) then open the model once created (found in app/Http/Models) and add the following under use HasFactory;:
protected $table = 'your_table_name';
protected $primaryKey = 'id'; // This is the column you usually set to PRIMARY
public $timestamps = true;
protected $fillable = [
'table_column',
'table_column',
];
To use the Model, import it into your Controller file like so use App\Models\Model; and then use it as so:
$flights = Flight::where('destination', 'Paris')->get();
Learn more about Models in Laravel here.
Using a Query Builder, not best practice
Import the DB facade in the controller like so use DB; then call upon it like so:
$db = DB::table('users')->where('name', 'John')->first();
Learn more about the Query Builder here.
I hope this helps, if not let me know how I can assist further.

Insert data into two columns of a table in Laravel Controller using sql

I have been trying to insert data using query into two columns of a table but there's something missing that its not sending data in the other column named booking_code.
It is inserting the booking_id into the table but not booking_code.
Here is the controller:
public function store(CreatePaymentRequest $request)
{
$input = $request->all();
$booking_id = $request->booking_id;
$booking_code = Booking::find($booking_id)->booking_code;
$this['booking_code'] = $booking_code;
$payment = $this->paymentRepository->create($input);
Flash::success('Payment saved successfully.');
return redirect(route('admin.payments.index'));
}
Please have a look at the Relevant Documentation Pages
You may also use the create method to save a new model in a single line. The inserted model instance will be returned to you from the method. However, before doing so, you will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment by default.
That means that you have to set, in Model, which fields you will allow to be "mass-assigned".
In your case, it will looks something like
class Booking extends Model
(...)
{
protected $fillable = ['booking_code', (...)];
}
(...)
In the code you provided though, I can't see how you build an $input variable so maybe the issue is there? Maybe it's just some typo.

Laravel protected attributes and Mutators

I have some problem with laravel and protected $attributes and mutators.
I have user ranking with points. I want add to User Model another attribution with ranking Position.
In user model I have public function like this:
public function getRankPositionAttribute(){
$userPoints= Ranking::where('user_id','=',$this->id)->first();
$userPosition = Ranking::where('points','>',$userPoints->points)->count()+1;
return $userPosition;
}
I also set:
protected $attributes = array('RankPosition'='');
But it's not working (I don't see value like RankPosition in attributes). Strange thing is that when I add (for example) value like this:
protected $attributes =array('test'=>'yes');
Laravel also don't see test...
But when I add this:
protected $appends = array('RankPosition');
and in my controller I find all user and get response to json then in json response i see value like RankPosition with the correct value... :(
What Im doing wrong? Why "my laravel" skips protected $attributes?
Please help me.
This is because if you provide protected $attributes in your class then Laravel doesn't override it when the source of attributes are the table . Here the source of $attributes is database column.
But when you do something like this:
$user = new User;
then you will see a test attribute.
So to dynamically adding the attributes you should use appends property on the model.

Jenssegers MongoDB dot notation in fillable

I'm trying to get the dot notation working in Jenssegers MongoDB package for Laravel. According this issue it's already been implemented:
link
But it doesn't seem to work in the latest version.
protected $fillable = ['title', 'some.data'];
Doesn't work. But if I open it all up it works fine.
protected $guarded = [];
So that works, not sure if this feature is still there or I need to pre filter my fields manually for now?
Nested fields are not currently supported in $fillable.
Unfortunately this means you have to do it manually. There are two ways to go:
If you have an embedded Some model, you can set $fillable on that, create/fill it with new data, then attach it to the parent model.
If you don't have/want a whole separate model for your subdocument, you would have to define e.g. $someFillable = ['data']; and use that to filter your new $some data prior to manually setting it on the model. You can basically just copy how Eloquent does it in its fill method.

Unit Testing in Laravel: Error when setting the Currently Authenticated User

In my Unit Test in Laravel I am setting the currently authenticated user with the code below. This is exactly how Laravel documented it on their website. I use the default User model which Laravel provide.
public function testLoggedInUserCanCreateCat() {
Route::enableFilters();
$user = new User(array(
'name' => 'john'
));
$this->be($user);
$this->call('GET', '/cats/create');
$this->assertResponseOk();
}
For some reason, when I run phpunit in SSH, I get the following error:
1) GlobalTest::testLoggedInUserCanCreateCat
Illuminate\Database\Eloquent\MassAssignmentException: name
Does anyone know whats goes wrong here? I searched for a couple of hours on the internet, but couldn't find any help..
The problem is in the error:
MassAssignmentException: name
You are trying to mass assign the variable name - but your model does not allow this.
Change your User model from this:
protected $fillable = [];
to this:
protected $fillable = ['name'];
You can read more about mass assignment here.

Categories