multiple images not storing in database - laravel

I am trying to upload multiple images on database but its not storing. when I var_dump the data I see the images but it's not storing in database.
the code for store the data is---
$ad = AdList::create([
"userId" => $userId,
"adTitle" => $request->data['title'],
"photos" => json_encode($imageList),
]);
var_dump($ad);
And the I got after var_dump is---
["photos"]=>
string(51) "["dodo (1)_1668406861.webp","dodo_1668406862.webp"]"
what is the reason for not storing in database? I am using laravel & vue
Ad_list model---
class AdList extends Model
{
use HasFactory, Sluggable;
protected $guarded = [];
// public $incrementing = false;
// protected $table = 'ad_lists';
// protected $keyType = 'string';
public function user(){
return $this->belongsTo(User::class, 'userId','id');
}
public function category(){
return $this->belongsTo(Category::class, 'catId','id');
}
public function subcategory(){
return $this->belongsTo(Category::class, 'subCatId','id');
}
public function businessPage(){
return $this->belongsTo(BusinessPage::class, 'userId','userId');
}
/**
* Return the sluggable configuration array for this model.
*
* #return array
*/
public function sluggable(): array
{
return [
'url' => [
'source' => 'title'
]
];
}
}

Maybe your table is not connected to your model. Try to add this:
protected $table
class AdList extends Model
{
use HasFactory;
use Uuid;
public $incrementing = false;
protected $table = 'adlist_table';
protected $keyType = 'string';
protected $guarded = [];
}
Try to add protected $table = ''adlist_table" in your model;

Related

Laravel resource: Get some of relations

There is a model User and a model Payments. I need to create a resource such that returns user with successful payment which is identified by a status fields. This is my solutions:
class User extends BaseModel
{
use HasFactory, SearchableTrait, SortableTrait;
protected $fillable = ['name', 'mobile', 'email', 'username', 'hash_id'];
public $searchable = ['name', 'mobile', 'email', 'id', 'user:referred'];
public $sortable = ['name', 'mobile', 'email', 'id'];
protected $table = 'users';
public function invoices()
{
return $this->hasMany(Invoice::class,'user_id');
}
}
and in controller
public function index()
{
$users = new User();
$users = $users::with(['invoices'])->filtered()->sorted();
return UserResource::collection($users->paginate());
}
and
<?php
namespace Modules\User\Transformers;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'mobile' => $this->mobile,
'invoices' => count($this->invoices()->where('status', 2999)->get()),
];
}
}
and model
class Invoice extends Model
{
protected $fillable = [];
protected $table = 'payment_invoices';
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function scopeSuccessful($query)
{
return $query->where('status', 2999);
}
}
It seems to be messy solution. I am looking for something to use the scope inside the model relation inside the resource. How can I do that?
in your controller you can just do this :
use Illuminate\Database\Eloquent\Builder;
public function index()
{
$users = User::with(['invoices'])->whereHas('invoices', function(Builder $query) {
$query->where('status', 2999);
});
return UserResource::collection($users->paginate());
}
<?php
class User extends BaseModel
{
use HasFactory, SearchableTrait, SortableTrait;
protected $fillable = ['name', 'mobile', 'email', 'username', 'hash_id'];
public $searchable = ['name', 'mobile', 'email', 'id', 'user:referred'];
public $sortable = ['name', 'mobile', 'email', 'id'];
protected $appends = ['success_payments']; // append this value in all queries
protected $table = 'users';
public function invoices()
{
return $this->hasMany(Invoice::class,'user_id');
}
//the function for it
public function getSuccessPaymentsAttribute(){
return App\Payment::where('user_id', $this->id)->where('status', 'success')->get(); //replace the attribute name or condition as per your db structure
}
}
You can use this in your User Model.

How to get nested relation record for ajax request in laravel?

I have Model Ticket in which user explain issue.
Ticket.php
class Ticket extends Model
{
protected $table = 'tickets';
/**
* #var array
*/
protected $guarded = [];
/**
* #var array
*/
protected $hidden = [
'created_at', 'updated_at'
];
public function ticket_replies()
{
return $this->hasMany(TicketReply::class, 'ticket_id');
}
public function ticket_assigned_agents()
{
return $this->hasMany(TicketAssignedAgent::class, 'ticket_id');
}
}
There is another model
TicketReply.php
class TicketReply extends Model
{
protected $table = 'ticket_replies';
/**
* #var array
*/
protected $guarded = [];
/**
* #var array
*/
protected $hidden = [
'created_at', 'updated_at'
];
public function staffs(){
return $this->belongsTo(Staff::class,'user_id');
}
public function ticket()
{
return $this->belongsTo(Ticket::class, 'ticket_id');
}
}
Now I want to get staff name from ticket reply
Query
public function getReplies($ticket_id)
{
$ticket = Ticket::where('id',$ticket_id)->with('ticket_replies')->first();
return response()->json($ticket);
}
I want to get staff name from TicketReply model in ajax success.
$.each(ticket.ticket_replies, function(index, reply) {
console.log(reply.staffs.name);
}
But it is not working. What can I do about it?
eager load the nested relationship
public function getReplies($ticket_id)
{
$ticket = Ticket::where('id',$ticket_id)->with(['ticket_replies','ticket_replies.staffs'])->first();
return response()->json($ticket);
}
and then do the same you are doing
$.each(ticket.ticket_replies, function(index, reply) {
console.log(reply.staffs.name);
}

Lazy eager loaded relationship missing in toArray()

Laravel 5.8
I am lazy loading an user with the related customer which has a one-to-one-relation with a crmaccount-object
The models are working so that when i retrieve the eager-loaded entity it shows all of the nested relationships.
One row later i use the "toArray()" method on that object and the output is missing the third-level-relations.
The only thing which maybe some kind of special regarding the "crmaccount"-model is that it holds a column which is json an has to be casted.
Any idea what is going on here?
All of these happens in a middleware. No difference if i use with or load.
public function handle($request, Closure $next)
{
$UserData = \Auth::user();
if($UserData){
$User = \App\Login::with(['role','customer','customer.crmaccount'])->find($UserData->id);
dump($User);
dd($User->toArray());
$UserData['isAdmin'] = false;
if($UserData['role']['name'] === 'Admin'){
$UserData['isAdmin'] = true;
}
$request->request->add(['UserData' => $UserData]);
}
return $next($request);
}
Login
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Login extends Authenticatable{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','customer_id','role_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/* */
public function Role(){
return $this->belongsTo('App\Role');
}
public function Customer(){
return $this->belongsTo('App\Customer');
}
/**
* [hasOpportunities Ruft alle Opportunities des Users ab. Da diese lediglich zwei Entitäten weiter sind, kann anstatt von dot-notated Lazy-Load auch die hasManyThrough-ORM-Methode genutzt werden]
* #return [hasManyThrough-Relation] [Die hasManyThrough-ORM-Beziehung]
*/
public function hasOpportunities(){
return $this->hasManyThrough(
'App\Opportunity',
'App\Customer',
'id',
'customer_id',
'customer_id'
);
}
/**
* [hasSalesreps Ruft alle SalesReps des Users ab. Da diese lediglich zwei Entitäten weiter sind, kann anstatt von dot-notated Lazy-Load auch die hasManyThrough-ORM-Methode genutzt werden]
* #return [hasManyThrough-Relation] [Die hasManyThrough-ORM-Beziehung]
*/
public function hasSalesreps(){
return $this->hasManyThrough(
'App\Salesrep',
'App\Customer',
'id',
'customer_id',
'customer_id'
);
}
}
Customer
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model{
public $timestamps = false;
protected $visible = ['id','name'];
protected $fillable = ['name'];
public function crmaccount(){
return $this->hasOne('App\Crmaccount');
}
public function Salesreps()
{
return $this->hasMany('App\Salesrep');
}
public function Prospects()
{
return $this->hasMany('App\Prospect');
}
public function Trees()
{
return $this->hasMany('App\Salesreptrees');
}
public function Opportunities()
{
return $this->hasMany('App\Opportunity');
}
public function User()
{
return $this->hasMany('App\Login');
}
}
Crmaccount
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Crmaccount extends Model{
public $timestamps = false;
protected $visible = ['id','name','crm_system','customer_id','crm_api_config'];
protected $fillable = [
'name','crm_system','customer_id','crm_api_config'
];
protected $casts = [
'crm_api_config' => 'array'
];
public function customer(){
return $this->belongsTo('App\Customer');
}
}
On every model, there is a protected $visible = []; and protected $hidden = [] attribute. These control the attributes that are available when the model is converted to an object, array or json. This includes relationships, as Laravel internally converts them to attributes, so omitting them from visible, or including them in hidden will cause them to not be available.
In Customer.php:
protected $visible = ['id','name'];
Since crmaccount is not in that array, only id and name will be available. Simply add crmaccount to the array to handle:
protected $visible = ['id','name', 'crmaccount'];
Alternatively, use hidden to explicitly set the attributes you don't want to show, and relationship, if loaded via ->with() will show by default.

How to relate two tables in Laravel 5.0

In a little example, I have 3 tables (2 of them are important).
My tables are PRODUCT, TRANSFER, WAREHOUSE
I want to transfer the PRODUCT from 1 WAREHOUSE to another and obviously this transfer has to be in the TRANSFER TABLE, My example model could be the next.
HERE THE ENTITY - RELATION - MODEL
Now I'm Using Laravel 5.0
And when I create the models im doing this, with TRANSFER model:
<?php namespace Sicem;
use Illuminate\Database\Eloquent\Model;
class TRANSFER extends Model{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'TRANSFER';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['id','ware_ori_id','ware_end_id','product_id'];
public function product(){
return $this->belongsTo('Sicem\Product');
}//THIS IS OK!
public function sourceware(){
return $this->belongsTo('Sicem\Warehouse\ware_ori_id');
}//I THINK THIS IS OK!
public function endware(){
return $this->belongsTo('Sicem\Warehouse\ware_end_id');
}//I THINK THIS IS OK!
}
Now, My question is here in my WAREHOUSE model, I don't what can I put:
<?php namespace Sicem;
use Illuminate\Database\Eloquent\Model;
class WAREHOUSE extends Model{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'WAREHOUSE';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['id','name'];
public function transfer(){
return $this->hasMany('Sicem\TRANSFER');
}//I supose this.
//But is or not necesary to have 2(two) functions for the relation in my TRANSFER model???????????
}
SICEM: is my project name
Please Help me.
class Product {
protected $table = 'PRODUCT';
protected $fillable = ['name'];
public function transfers()
{
return $this->hasMany(Transfer::class);
}
public function transfer($warehouse_from_id, $warehouse_to_id)
{
return Transfer::create([
'product_id' => $this->id,
]);
}
}
class Transfer {
protected $table = 'TRANSFER';
protected $filalble = ['ware_ori_id', 'ware_end_id', 'product_id'];
public function warehouse_from()
{
retrun $this->belongsTo(Warehouse::class);
}
public function warehouse_to()
{
return $this->belongsTo(Warehouse::class);
}
public function product()
{
return $this->belongsTo(Product::class);
}
}
class Warehouse {
protected $table = 'WAREHOUSE';
protected $fillable = ['name'];
}
So you need to do something like this:
$warehouseFrom = Warehouse::find(1);
$warehouseTo = Warehouse::find(2);
$product = Product::find(23);
$product->transfer($warehouseFrom->id, $warehouseTo->id);

Laravel eloquent add extra models to hasMany

I have a user Model and each user has multiple licenses. There are 2 default licenses that apply to all users that are not in the licenses table and they need to be created on the fly using certain data contained in the User model.
How can I create 2 licenses each time I'm getting a user's licenses and add it to the output of licenses()?
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
protected $table = 'users';
public $timestamps = false;
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function licenses()
{
return $this->hasMany('App\License', 'user_id', 'id')->where('deleted', '=', '0');
}
}
You could create an extra function in the model where you call the licenses and add the extra licenses.
Remember to test all places where you use this function so no strange stuff will happen.
<?php
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
protected $table = 'users';
public $timestamps = false;
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
// HasMany function
public function _licenses()
{
return $this->hasMany('App\License', 'user_id', 'id')->where('deleted', '=', '0');
}
// New licenses function
public function licenses()
{
// Get licenses from database
$licenses = $this->_licenses;
// Add other lisences
$licenses = $licenses->add(new License([ "user_id" => $this->id, "name" => "foo" ]));
$licenses = $licenses->add(new License([ "user_id" => $this->id, "name" => "bar" ]));
// Return the new collection
return $licenses
}
}

Resources