I have code updating a collection as follows
Transaction::whereIn('id', $inProcessIds)
->update([
'transfer_status' => SaleTransaction::TRANSFER_STATUS_TRANSFERRED
]);
In Transaction I have relation to another model
public function sale_offer() {
return $this->hasOne('App\SaleOffer', 'sale_offer_id', 'id');
}
What I want to do is update related model at once when I updating Transaction
Here's what I tried to do is
Transaction::whereIn('id', $inProcessIds)->with('sale_offer')
->update([
'transfer_status' => SaleTransaction::TRANSFER_STATUS_TRANSFERRED
'transaction.sale_offer => 1'
]);
or
Transaction::whereIn('id', $inProcessIds)->sale_offer()
->update([
'transfer_status' => SaleTransaction::TRANSFER_STATUS_TRANSFERRED
'transaction.sale_offer => 1'
]);
]);
You can update related model by extract sale_offers ids from Transaction table then update sale_offer :
$sale_offer_ids=Transaction::whereIn('id', $inProcessIds)->with('sale_offer')->pluck('sale_offer_id')->toArray();
then update sale offer :
SaleOffer::whereIn('id',$sale_offer_ids)->update(['amount_sent'=>$amount_sent]) ;
Related
Can be possible to store a file uploaded to a related table?
Scenario: I have a usres table in database and another one pictures. Users Model have the following function
public function picture()
{
return $this->hasOne(Picture::class);
}
And the Picture Model have the following function.
public function user_picture()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
Is possible to store the picture in pictures database table (id, user_id, img_path) from the UserCrudController store() function?
try something like this
public function store(Request $request)
{
Picture::create([
'user_id' => // get the user id from $request or auth()->user(),
'img_path' => $request->file('image')->store('images', 'public'),
]);
return // your view or something else
}
Let's say it is a registration form that need to insert an image. Instead of using the Picture model directly you can just do this :
public function store(Request $request)
{
$request->validate(...);
$user = User::create(...);
//It will ensure that the image belongs to the user.
$user->picture()->create([
'image_path' => $request->file('image')->store('images');
])
}
I resolved the issue with the following steps.
As per Laravel Backpack I added the input field in the Blade:
#include('crud::fields.upload', ['crud' => $crud, 'field' => ['name' => 'img1', 'label' => 'Image 1', 'type' => 'upload', 'upload'=> true, 'disk'=>'uploads', 'attributes' => ['id' => 'img1', 'capture' => 'user']]])
After this I added the function in the User Controller as follow:
$request->validate(['img1' => 'mimes:jpg,png,jpeg|max:5120']);
$fileModel = new Picture;
if($request->file()) {
$fileName1 = time().'_'.$request->img1->getClientOriginalName();
$filePath1 = $request->file('img1')->storeAs('uploads', $fileName1, 'public');
$fileModel->name = time().'_'.$request->img1->getClientOriginalName();
$fileModel->img1 = '/storage/' . $filePath1;
$fileModel->save();
}
With these lines of code I was able to store the related Picture with the User.
Thank you all for the guidelines.
I use laravel 8 and backpack 4.1 for laravel. I have to add in one column more then one comma-separated-values. I have one pivot table with 2 foreign keys. The user can see with foreign key the available objects. I have to put all available objects into one column in setupListOperation() in CrudController of the user. How can I do it?
UserModel:
public function Objects(): belongsToMany
{
return $this->belongsToMany(Object::class);
}
CRUD::column('object_id')
->type('relationship')
->relation_type('BelongsToMany')
->model(Object::class)
->entity('name')
->label('Objects');
Thank you for your answers in advance.
I have found another method for the user crud. This method supposed to get the values from the method of the model.
$this->crud->addColumn(
[
// run a function on the CRUD model and show its return value
'name' => 'rentalObjects',
'label' => 'RentalObjects', // Table column heading
'type' => 'model_function_attribute',
'function_name' => 'getRentalObjects',
'attribute' => 'name'
]);
Method in the model User:
public function getRentalObjects(): string
{
$users = User::all();
foreach ($users as $user) {
$rentalObjects = $user->rentalObjects;
foreach ($rentalObjects as $rentalObject) {
$objectsNames = $rentalObject->name;
}
$objects = implode(",", array($objectsNames));
}
return $objects;
}
I coudn't see the new column on the small screen und thought, that the column wasn't in the table. By backpack one can choose the columns, if the screen is small.
The problem was solved:
$this->crud->addColumn([
'label' => 'Objekte', // Table column heading
'type' => 'select_multiple',
'name' => 'rentalObjects', // the method that defines the relationship in your Model
'entity' => 'rentalObjects', // the method that defines the relationship in your Model
'attribute' => 'name', // foreign key attribute that is shown to user
'model' => 'App\Models\RentalObject', // foreign key model
]);
i'm developping a social app using React in the frontend and laravel in the backend.
I'm trying to receive all posts with their likes,users,comments. I have these relation ships:
1/ User model has many posts and Post model belongs to a user.
2/ Post model has many likes
3/ Post model has many comments and one comment belongs to a user.
When getting all posts back, im succefully getting its likes and users information, but for comments i wanna get the user's comment. So i did $posts->comments->user->user_name
And then, i got the error: Property [user] does not exist on this collection instance. But when i tried to get comments infos, it worked normally($posts->comments)
My comment relation in Post model:
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
My user relation in Comment Model:
public function user()
{
return $this->belongsTo('App\Models\User');
}
My method in PostController when i'm trying to get all posts:
public function allPosts()
{
$posts = Post::with('user','likes','comments')->get();
if($posts->count() < 1) {
return response()->json([
'success' => false,
'message' => 'There are no posts!'
]);
}else {
return response()->json([
'success' => true,
'data' => PostResource::collection($posts),
'message' => 'Succefully retreived all posts!'
]);
}
}
As you noticed i'm sending the Data through a Resource, so My PostResource's method :
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'user_id' => $this->user_id,
'content' => $this->content,
'image_path' => $this->image_path,
'user' => $this->user,
'likes' => $this->likes->count(),
'isLiked' => $this->likes->where('user_id', auth()->user()->id)->isEmpty() ? false : true,
'comment_user' => $this->comments->user->user_name,
'created_at' => $this->created_at->format('d/m/y'),
'updated_at' => $this->updated_at->format('d/m/y')
];
}
As i said, everything is okey, just for comment_user it says:Property [user] does not exist on this collection instance, and when i tried to get only comments info it worked:
'comments' => $this->comments,
Any help please? and thnx in advance.
Maybe you need to add relation user() to Post model?
i'm trying to make inquiry form where costumer fill up form then check the value on the checkbox then once they submit form will send email to me listing all the information the customer selected, now problem is i want to change this[event_id,requirement_id] instead of id replace it with name those two id parameter is from my two model listed below.
Model:
Event:[id,name]
Requirement:[id,name]
Controller:
public function store(Request $request)
{
$summary=[
'name' => $request->fullname,
'email' => $request->email,
'company' => $request->company,
'event' => $request->event_id,
'requirement' => $request->requirement_id
];
return $summary;
Mail::send('emails.contact-message',[
],function($mail) use($summary){
$mail->from('myemail#gmail.com', 'tester');
$mail->to('myemail#gmail.com')->subject('Contact Message');
});
return redirect()->back();
}
This is the result of my return request:
{"name":"myname","email":"myemail#gmail.com","company":"mycompany","event":["1","2"],"requirement":["1","2"]}
As you can see the array Event has value of 1 and 2 i wanted to replace it with its name output should be [Wedding,Birthday] i'm sorry for my bad english hope you understand me..
Well, you'd need to pull the name from your models.
The following should do the trick:
$events = App\Event::whereIn('id', $request->event_id)
->get()
->pluck('name')
->toArray();
$requirements = App\Requirement::whereIn('id', $request->requirement_id)
->get()
->pluck('name')
->toArray();
Obviously, replace name in the above example with the actual name field in your models. This is just an example.
$events and $requirements will both be an array containing the names matching the ids you are supplying in your request.
You also need to change your $summary array as follows:
$summary = [
'name' => $request->fullname,
'email' => $request->email,
'company' => $request->company,
'event' => $events
'requirement' => $requirements
];
One of two similar store methods doesn't work. Could you clarify this for me?
Relations
A Team hasMany Users <> A User belongsTo a Team
A User hasMany Characters <> A Character belongsTo a User
Working Code (CharacterController)
public function store()
{
$fighters = Fighter::pluck('name')->toArray();
$this->validate(request(), [
'name' => 'required|min:3|max:25|alpha_num|not_in:'.Rule::notIn($fighters).'unique:characters',
'fighter' => 'required|in:'.Rule::in($fighters),
]);
auth()->user()->characters()->save(new Character([
'name' => request('name'),
'fighter' => request('fighter'),
]));
return redirect()->route('character.index');
}
Not Working (TeamController)
public function store()
{
$this->validate(request(), [
'name' => 'required|min:3|max:25|alpha_num|unique:teams',
]);
auth()->user()->team()->save(new Team([
'name' => request('name'),
'fame' => 0,
]));
return redirect()->route('team.index');
}
Questions
Why is the same method not available? Is it relation stuff?
Is the create method better? Should I try to use it?
Thought I know what I'm doing, now it turns out I don't...
Thank you for helping.
team() is a belongsTo relation, you probably have a team_id col in your user table which you want to associate with the team.
public function store()
{
$this->validate(request(), [
'name' => 'required|min:3|max:25|alpha_num|unique:teams',
]);
// create and save team
$team = new Team([
'name' => request('name'),
'fame' => 0,
]);
$team->save();
// associate current authenticated user with team (set foreign key) and save user
auth()->user()->team()->associate($team)->save();
return redirect()->route('team.index');
}