How to seed in Laravel? - laravel

I'm trying to seed my DB following the instructions on http://laravel.com/docs/migrations#database-seeding:
class DatabaseSeeder extends Seeder {
public function run()
{
$this->call('UserTableSeeder');
$this->command->info('User table seeded!');
}
}
class UserTableSeeder extends Seeder {
public function run()
{
DB::table('users')->delete();
User::create(array('email' => 'foo#bar.com'));
}
}
I'm a bit confused by this. What is User in User::create(array('email' => 'foo#bar.com'));?

The create method inserts a record in the database (Seeding is a way of pre-populating the database).
It basically invokes the Model named User and uses the Create() method in a static manner by passing an array and returns an instance of the model representing the user entity with the passed details.

Related

laravel eloquent relationship for indirectly related model

I want a relationship where two unrelated models are linked together with a linker model.
My tables are like:
card table
id(pk)
name
User table
id(pk)
username
password
card_id(fk)
Feature table
id(pk)
name
card_id(fk)
How can i define an eloquent relationship to access all the features of user's card from user model like this:
class User extends Model
{
use HasFactory;
public function features(){
return $this->relatonship_statement;
}
}
and when I tried in Card Model:
class Card extends Model
{
use HasFactory;
public function features(){
return $this->hasMany(Feature::class);
}
}
and in User model:
class User extends Model
{
use HasFactory;
public function card(){
return $this->belongsTo(User::class);
}
public function features(){
return $this->card->features;
}
}
I get error:
App\Models\User::features must return a relationship instance.
What you really want is an accessor function, not a relationship. This is how you would do to achieve what you want.
class User extends Model
{
use HasFactory;
protected $appends = ['features']; //to append features in the response json
public function card(){
return $this->belongsTo(Card::class); //editted User to Card
}
public function getFeatures(){ //accessor method
return $this->card->features()->get();
}
}
sample result after returning user in a controller function
return User::query()->with('card')->first();
However, the right way is to access the features through the Card Relationship because these two models have a direct relationship.

Laravel: How to define belongsTo in a MorphPivot?

In my project there is a Many-to-Many polymorphic relationship (Many instances of a model called Package (morphedByMany) can contain many different content types (each MorphedToMany).
I've created a pivot table containing some additional fields that I'll need to access and query by, and so I've decided that the best thing would be to create a Pivot model by extending the MorphPivot.
Querying is now easy enough, however, I can't access the content through a relation (which I can do if i query the App\Packages::findOrFail(1)->contentType()). I know I should declare that the pivot belongsTo the contentType, but I'm not sure how to go about it seeing as it could belong to any of the morphed contentTypes.
EDIT
Code blocks as requested
Content1
class Song extends Model
{
public function packages()
{
return $this->morphToMany('App\Package', 'packageable')->withPivot('choice')->using('App\PackageContent');
}
Content2
class Video extends Model
{
public function packages()
{
return $this->morphToMany('App\Package', 'packageable')->withPivot('choice')->using('App\PackageContent');
}
Package
class Package extends Model
{
public function songs()
{
return $this->morphedByMany('App\Song', 'packageable')->withPivot('choice')->using('App\PackageContent');
}
public function videos()
{
return $this->morphedByMany('App\Video', 'packageable')->withPivot('choice')->using('App\PackageContent');
}
MorphPivot
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\MorphPivot;
class PackageContent extends MorphPivot
{
protected $table = 'packageables';
Pivot table migration
public function up()
{
Schema::create('packageables', function (Blueprint $table) {
$table->integer('package_id');
$table->integer('packageable_id');
$table->string('packageable_type');
$table->integer('choice');
});
}

How to write a custom function in a model?

There is a model data:
class Order extends Model
{
}
How to write a custom method inside the Order class so that it can be called in constructor like this:
Order::myMethod()
Order->myMethod()
Where myMethod is:
public function myMethod() {
return DB::query(<SQL QUERY>);
}
Purpose is to move SQL queries inside model's class, that don't mess this code in controllers.
Rather create a custom function in Model, You can use traits to achieve the desired output.
Please follow either steps:-
https://medium.com/#kshitij206/traits-in-laravel-5db8beffbcc3
https://www.conetix.com.au/blog/simple-guide-using-traits-laravel-5
Guess you are asking about the static functions:
class Order extends Model {
public static function myMethod() {
}
}
and you can call it anywhere like
Order::myMethod();
You can achieve the desired behavior using magic methods __call and __callStatic
if your real method is static you can use __call() to intercept all "non static" calls and use it to call the static and use __callStatic to forward the calls to a new instance to that class .
Your methods should be always static because if a non static method exists and you are calling it statically php raises an error
Non-static method Foo::myMethod() should not be called statically
No problem if your method is static
class Order extends Model {
public static function myMethod() {
return static::query()->where(...)->get(); // example
}
public function __call($name, $arguments) {
return forward_static_call_array([__CLASS__, $name], $arguments);
}
public static function __callStatic($name, $arguments) {
return call_user_func_array([app(__CLASS__), $name], $arguments);
}
}
(new Order())->myMethod();
Order::myMethod();
I can't understand your exact problem is. but if you are using laravel, then you can write custom method inside the ABC model like this
class ABC extends Model
{
//here is your fillable array;
public function abc()
{
//Here is your Eloquent statement or SQL query;
}
}
just call this abc() method inside the controller like this
use ABC;
class AbcController extends Controller
{
private $_abc; // it is private variable
// this is constructor
public function __construct(ABC $abc)
{
$this->_abc= $abc;
}
public function abcMethod()
{
$this->_abc->abc();
}
}
Thanks
I don't believe I'm understanding your intention. You've stated:
Purpose is to move SQL queries inside model's class, that don't mess this code in controllers.
Why does the Order->myMethod() need calling inside the constructor? If you're trying to design your data access layer to work efficiently, you can use data repositories.

Trying to access model from another model returns null

I have the following two model classes:
class CarRequest extends Model
{
public function model()
{
return $this->belongsTo('App\CarModel', 'model_id');
}
}
class CarModel extends Model
{
public function brand()
{
return $this->belongsTo('App\CarBrand', 'brand_id');
}
}
class CarBrand extends Model
{
public function models()
{
return $this->hasMany('App\CarModel');
}
}
Car request has car model and car model has car brand.
When I try to access the brand as the following:
$request->model->brand
It returns null, however
$request->model
returns the car model normally.
Also, accessing the brand from the model directly without the car request works fine as well.
What am I doing wrong?
Your models are all good.
$request->model
This works because you are using the object as is. However, if you wish to access the object's properties you have to add the parenthesis.
Perhaps try:
$request->model()->brand
This allows you to access the brand property in the collection model.

Eloquent : delete rows from multiple table with same id

I am a bit new to Laravel. I am trying to delete a project from a table along with its images and plans from 2 other tables. How to do this in Laravel Eloquent?
Here is the delete controller of the project:
public function destroy($id)
{
$project = Projects::findOrFail($id);
$project->delete();
return Redirect::to('admin/view-project')->with('message', 'Project deleted successfully');
}
How can I get this to be done from the model? I didn't understand that.
Here is the Projects model:
class Projects extends Eloquent implements UserInterface, RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'project_info_arabic';
public function projectImages()
{
return $this->hasMany('ProjectsImage');
}
public function projectPlans()
{
return $this->hasMany('ProjectsPlans');
}
}
Can kindly anybody help?
The better way when thinking about data consistency is the implementation of foreign keys on the database layer. That does it automatically for you and you don't need to think about it anymore.
See https://laravel.com/docs/5.3/migrations#foreign-key-constraints
You could try model events in laravel.Check this
class Projects extends Eloquent implements UserInterface, RemindableInterface
{
public static function boot()
{
parent::boot();
Projects::deleted(function($project)
{
$project->projectImages()->delete();
$project->projectPlans()->delete();
});
}
}

Resources