I am trying to create model named CustomDataStore (models/custom_data_store.php) and it is extending Eloquent, so table is named as custom_data_stores, but it gives me error.
Eloquent wants table named customdatastores. Of course I can set manually table name, but how can I set such name automatically?
For it to be made automatically your model would have to be in models/custom/data/store.php
class Custom_Data_Store extends Eloquent
{
}
I have noticed that laravel's eloquent can't really "see" if there are underscores on the model's filename. I'm not really sure what's happening inside (still a newbie), but this is only based on my observation..
what I did was
I have two different models, named tblReport_date.php and tblReportdate.php, both have the same codes except that they are pointed at different tables.
tblReportdate.php code:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class tblReportdate extends Eloquent implements UserInterface, RemindableInterface
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'tblClients';
...rest of the codes...
tblReport_date.php code:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class tblReportdate extends Eloquent implements UserInterface, RemindableInterface
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'tblReport_date';
...rest of the codes...
on the controller, I have this code
$db = tblReportdate::all();
return View::make('db.index')->with('db', $db);
the result is that it will only load tblReportdate.php and not tblReport_date.php
I tried extracting tblReport_date.php alone and tested it.. it always returns an error, regardless of the class name, etc..and IDK why. If someone can explain this pls comment it out.. anyways, just avoid putting underscores on filenames XD
Related
I am implementing Laravel 5.3 Notifications at the moment which is working very nice.
At the moment I am using 'email' as a notifications channel but I want to add 'database' too. I am using different databases/connections for languages and want to store the notifications in a central database / Connection.
How do I use a different database connection for notifications?
I already tried creating a Notifications model but that did not work:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Notifications extends Model
{
protected $connection = 'system';
}
Hackish solution. But tried and tested on a MongoDB connection.
What needs to be modified;
The Notifiable trait
The DatabaseNotification model
Optionally (nothing changes if you are using mysql) modify the HasNotifications trait
Modify the DatabaseNotificationCollection.Again this is useful for a non-mysql connection
Step One : Create a custom Notifiable Trait
Copy the contents from Illuminate\Notifications\Notifiable and create a new file in your custom path...say App\Overrides\Notifications\Notifiable.
Your file will feature two changes...the namespace and you have to load the RoutesNotifications trait since we are not copying it over.
<?php
namespace App\Overrides\Notifications;
use use Illuminate\Notifications\RoutesNotifications;
trait Notifiable{
//The rest of the code remains
}
Step Two : Create a custom DatabaseNotification model
Follow the same procedure as above and copy the contents of the Illuminate\Notifications\DatabaseNotification file to the custom path that we created above...App\Overrides\Notification\DatabaseNotification
This is a standard Eloquent model and the connection change actually happens here
<?php
namespace App\Overrides\Notification;
//Use this if on mongodb.otherwise use to Illuminate\Database\Eloquent\Model
use Jenssegers\Mongodb\Eloquent\Model;
use Illuminate\Notifications\DatabaseNotificationCollection;
class DatabaseNotification extends Model
{
protected $connection = 'YOUR_CONNECTION_NAME_GOES HERE';
}
As of this point this should work if you are on a mysql connection.
To try this out change the Notifiable trait on the user model to use App\Overrides\Notifications\Notifiable. The notifications will use the connection you specified.
Users of MongoDB will have to take extra steps since the most popular driver I know of does not yet support MorphMany relations which are put to use for Laravel notifications.
Since that is not the asked question we leave it at that :-)
On Laravel 5.7 based on #Bernard answer
User.php
<?php
namespace App;
// implement the override Notifiable trait
use App\Traits\Override\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
}
Notifiable.php
<?php
namespace App\Traits\Override;
use Illuminate\Notifications\RoutesNotifications;
trait Notifiable
{
use HasDatabaseNotifications, RoutesNotifications;
}
HasDatabaseNotifications.php
<?php
namespace App\Traits\Override;
use App\Models\Override\MultiConnectionDatabaseNotification;
trait HasDatabaseNotifications
{
/**
* Get the entity's notifications.
*
* #return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function notifications()
{
return $this->morphMany(MultiConnectionDatabaseNotification::class, 'notifiable')->orderBy('created_at', 'desc');
}
/**
* Get the entity's read notifications.
*
* #return \Illuminate\Database\Query\Builder
*/
public function readNotifications()
{
return $this->notifications()->whereNotNull('read_at');
}
/**
* Get the entity's unread notifications.
*
* #return \Illuminate\Database\Query\Builder
*/
public function unreadNotifications()
{
return $this->notifications()->whereNull('read_at');
}
}
MultiConnectionDatabaseNotification.php
<?php
namespace App\Models\Override;
use Illuminate\Notifications\DatabaseNotification as DatabaseNotification;
class MultiConnectionDatabaseNotification extends DatabaseNotification
{
// set your preferred connection here
protected $connection = 'oracle';
}
It's pretty simple, Just add protected $connection = 'YOUR CONNECTION NAME'; at Illuminate\Notifications\DatabaseNotification
That's all and it will work :)
You don't need to create new models if you are going to use one notification table with same connection.
My code will works if ur using different connection for USER model.
I have a model in Laravel called Checkout. It is just tied to a table in the database called checkouts.
namespace App;
use Illuminate\Database\Eloquent\Model;
class Checkout extends Model
{
protected $primaryKey = 'id';
protected $table = 'checkouts';
}
What I would like to do is add a field to the model that isn't a field in the table. Is this even possible?
If need be, I will completely manually build the model, but I have never seen any examples of that either.
Any help would be greatly appreciated! Thanks,
You can use Laravel's Accessor as:
public function getSomeExtraFieldAttribute()
{
return 2*4; // just for exmaple
}
Then you can access it using
$checkout = App\Checkout::find(1);
$checkout->some_extra_field;
I'm building my first Laravel application, and I'm trying to figure out how I should be hashing passwords at a model level.
The issue is, when trying to use the Laravel Hash:: class, it can't be found. I've attempted to look up the relevant API documentation, but can't find anything apart from some references to Illuminate namespace classes - and from what I gather Hash:: should be globally available?
I'm new to PHP namespacing, and I'm guessing this may have something to do the with the issue, as the error states it's looking for App\Hash and I know it's not part of the App namespace, but the Illuminate one.
Here's my code:
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['first_name', 'last_name', 'default_currency', 'default_timezone', 'default_location', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function setPasswordAttribute($value) {
$this->attributes['password'] = Hash::make($value);
}
}
Any help in figuring out the route cause of this, and any suggestions would be greatly appreciated!
You just need to import the \Hash class, or call it with \Hash::make(). Just doing Hash as you are looks within the namespace of the class you're calling it from. The Hash class is part of the root namespace, or \.
\Hash is a 'Facade' class, which just basically allows you to call static globally, from anywhere, without necessarily needing to import the original class. More information can be found on the documentation page for Facades.
use Hash;
after namespace App include use hash line it must work.
I am using this Laravel 4 package for interacting with the Xero accounting application: https://github.com/Daursu/xero
In the GitHub README, it says that you can extend the package easily by using the following code:
namespace Daursu\Xero;
class CreditNote extends BaseModel {
/**
* The name of the primary column.
*
* #var string
*/
protected $primary_column = 'CreditNoteID';
}
I tried adding this as a new Model, but Laravel gives me a Class not found error.
I'm assuming this is a namespacing issue a but can't seem to get it right. I have tried using \Darsu\Xero and also \Darsu\Xero\BaseModel, and other various combinations with and without the initial \.
Any tips on how to do this right?
Easiest way to achieve your intentions:
1) Create a file CreditNote.php in app\models
2) Put the following code in the above file:
use Daursu\Xero\BaseModel;
class CreditNote extends BaseModel {
/**
* The name of the primary column.
*
* #var string
*/
protected $primary_column = 'CreditNoteID';
}
3) Whenever you need to use the CreditNote model, use $creditNote = new CreditNote();
Recently I came across a class that uses use statement inside of the class definition.
Could someone explain what exactly does it do - as I can't find any information about it.
I understand that it might be a way of moving it away form a global scope of the given file, but does it perhaps allow the given class inherit from multiple parent classes as well - since extends only allows one parent class reference?
The example I saw was in the User model of the original installation of Laravel:
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
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');
}
and I've seen some examples of this model actually using methods included within the UserTrait class - hence my suspicion, but would really like to find out more about the meaning of the enclosed use statements.
PHP documentation says:
The use keyword must be declared in the outermost scope of a file (the
global scope) or inside namespace declarations. This is because the
importing is done at compile time and not runtime, so it cannot be
block scoped. The following example will show an illegal use of the
use keyword:
followed by the example:
namespace Languages;
class Greenlandic
{
use Languages\Danish;
...
}
which would indicate that it is an incorrect use of the use keyword - any clues?
They are called Traits and are available since PHP 5.4. They are imported into another class or namespace using use keyword which is included since PHP 5.0 like importing a regular class into another class. They are single inheritance. The primary reason for the implementation of traits is because of the limitation of single inheritance.
For more details see the PHP trait manual: