Save One-to-Many Relationship in Laravel 6 - laravel

I have two Table that Transfer and Product that link One-to-Many Relationship. I'm to create relationship between Transfer and Product like Pics Below.
that get Selected Dropdown Product when Click Search.... and When Click Create save relationship Product into Transfers..
My Transfer Model
public function products()
{
return $this->hasMany(\App\Product::class);
}
My Product Model
public function transfer()
{
return $this->belongsTo(\App\Transfer::class);
}
in TransferController
public function store(Request $request)
{
$request->validate([
'from_location' => 'required',
'to_location' => 'required',
'status' => 'required',
'description' => 'nullable',
'shipping_charge' => 'nullable',
]);
$transfer = new Transfer();
$transfer->branch_id = auth()->user()->id;
$transfer->from_location = $request->input('from_location');
$transfer->to_location = $request->input('to_location');
$transfer->status = $request->input('status');
$transfer->shipping_charge = $request->input('shipping_charge');
$transfer->save();
// $products = new Product();
// $products->name = $request->input('')
return response()->json(['created' => true]);
}
I think its a dummy question, but i stuck 3 days with it. I'll appreciate of all Ur help...

You need to post the product_ids to backend that you selected,
and just update the relationship:
...
$transfer->shipping_charge = $request->input('shipping_charge');
$transfer->save();
Product::whereIn('id', $product_ids)->update(['transfer_id' => $transfer->id]);
If your products are all new, you can use saveMany:
$products = array(
new Product(['name' =>'product1', ...]),
new Product(['name' => 'product2', ...])
);
...
$transfer->save();
$transfer->products()->saveMany($products);

Related

How to upload file in relationship hasOn<->belongsTo Laravel Backpack

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.

How to set default value for a field in laravel `morphMany` relationship (not database tier)

I have a model File where save files of my app, it like:
class File{
public const IMAGE_TYPE = 'image';
public const AUDIO_TYPE = 'audio';
public const VIDEO_TYPE = 'video';
public const APPLICATION_TYPE = 'application';
protected $fillable = ['path', 'type', 'description', 'order', 'filable_type', 'filable_id'];
}
Suppose I have an Post model, it like:
class Post{
public function videos(){
return $this->morphMany(File::class, 'filable')
->where('type', File::VIDEO_TYPE);
}
public function images(){
return $this->morphMany(File::class, 'filable')
->where('type', File::IMAGE_TYPE);
}
}
When I get data of above relationships it's okay
But when I create a new file of post it is repetitive and easily make mistakes
$post->images()->create([
'path' => 'my-image.jpg',
'type' => File::IMAGE_TYPE,
]);
$post->videos()->create([
'path' => 'my-image.mp3',
'type' => File::VIDEO_TYPE,
]);
I want it look like:
$post->images()->create([
'path' => 'my-image.jpg',
]);
$post->videos()->create([
'path' => 'my-image.mp3',
]);
I don't need declare type per creating videos or images of a post.
How I can accomplish this!
Modal
// Change morphMany to hasMAny
public function videos()
{
return $this->hasMany(File::class, 'fileable')
->where('type', File::IMAGE_TYPE);
}
Controller
// You can do this
$vedioToCreate = $post->videos();
$vedioToCreate->path = 'my-image.mp3';
$vedioToCreate->save();
// Or you can do this
$post->videos()->create([
'path' => 'my-image.mp3',
]);

how to perform bulk update with change check in laravel?

I am using laravel, I am using this code in the update function. works fine, but is it possible to save lines of code with bulk insertion?
Example: $product->update($request->all());
But first check if they have sent new data to update.
My Function Update:
public function update(ProductUpdateRequest $request, Product $product)
{
$data = Product::findOrFail($product->id);
$data->category_id = $request->category_id;
$data->name_product = $request->name_product;
$data->description = $request->description;
$data->stock = $request->stock;
$data->price_buy = $request->price_buy;
$data->price_sale = $request->price_sale;
$data->status = $request->status;
if ($data->isDirty()) {
$data->update($request->all());
return response()->json([
'color' => 'green',
'message' => 'CATEGORY EDIT'
]);
} else {
return response()->json([
'color' => 'red',
'message' => 'NO CHANGE DETECTED'
]);
}
}
You can use fill() method to fill the model with data without committing to database. Do the dirty check and then save. Eg:
public function update(ProductUpdateRequest $request, Product $product)
{
$product->fill($request->all()); //no need to use product->find since $product with the id is already injected
if ($product->isDirty()) {
$product->update($request->all()); //or use $product->save(); since model is alraedy filled with new data
return response()->json([
'color' => 'green',
'message' => 'CATEGORY EDIT'
]);
} else {
return response()->json([
'color' => 'red',
'message' => 'NO CHANGE DETECTED'
]);
}
}
Do note that save method actually checks if the model is dirty. So, if you do not want to send custom messages based on whether the model was changed or not, you could just call save() instead of update() without the dirty check.

Need help about passing club_id in player controller

I'm making football blog and I want to make that i can create players, but i have problem with it because i get eroor "Call to a member function players() on null" i know where is problem but i dont know how to solve it, I have similar problem with comments and posts but i done it and now again same problem but it dont work
//PlayersController
public function store(Request $request)
{
$this->validate($request, [
'fname' => 'required',
'lname' => 'required',
'age' => 'required',
'country' => 'required',
'position' => 'required',
'image' => 'image|nullable|max:1999',
'text' => 'required'
]);
//create Player
$player = new Player;
$player->fname = $request->input('fname');
$player->lname = $request->input('lname');
$player->age = $request->input('age');
$player->country = $request->input('country');
$player->position = $request->input('position');
$player->image = $fileNameToStore;
$player->text = $request->input('text');
$club = Club::find($request->get('club_id')); //problem
$club->players()->save($player); //problem
}
//club model
public function players()
{
return $this->hasMany(Player::class);
}
//player model
public function club()
{
return $this->belongsTo(Club::class);
}
Sounds like $club is coming back null and that's why Laravel is giving an error when you try to use players() on it. Have you checked that $request->get('club_id') is giving you what you expect?
Also don't forget that your new $player doesn't fully exist yet in the database until you do $player->save(). Not sure if you can save it and also create its relationship to $club in one line. You could try saving it first, and then attaching it.

Two store() methods, one doesn't work (Call to undefined method save())

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');
}

Resources