Need help about passing club_id in player controller - laravel

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.

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.

Validating form comaring two fields values

I'm trying to find Laravel 8 documentation on how to validate comparing two fields to each other. I'm creating an app that allows creating matches from teams in a database table, using the create() method in the controller. I looked into Laravel #Validation, even #Custom Validation Rules, but I can't find anything when comparing the two fields.
public function store(Request $request)
{
$validatedData = $request->validate([
'local_team' => 'required',
'local_score' => 'required|numeric',
'visitor_team' => 'required',
'visitor_score' => 'required|numeric',
]);
$score = new Score();
$score->local_team = $request->local_team;
$score->local_score = $request->local_score;
$score->visitor_team = $request->visitor_team;
$score->visitor_score = $request->visitor_score;
$score->save();
$new = true;
return redirect()->route('scores.show',
['id' => $score->id, 'new' => true]);
}
In my case, the 'local_team' and 'visitor_team' fields should be different. Any clue on how to do it?

Save One-to-Many Relationship in Laravel 6

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

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

Laravel Simultaneously input one to many in database

I have a card, this card has tags. So a Card has many tags and a Tag belongsTo a Card.
A user fills a form. He gives both the information for the card aswell as the tags.
Now I need to give each tag the information 'card_id' so it can be connected.
Now is my problem that I don't know this 'card_id' yet because the database did not yet assign a id as they are both being created simultaneously.
My situation:
public function create(Request $request)
{
$this->validate($request,[
'function' => 'max:255',
'description' => 'max:255',
'rate' => 'max:255',
'location' => 'max:255'
]);
$card = new Card;
$card->user_id = Auth::id();;
$card->function = $request->function;
$card->description = $request->description;
$card->rate = $request->rate;
$card->location = $request->location;
// I also tried this: $card->tag()->saveMany($tagsArray); (Did not work)
$card->save();
$tagsArray = explode(',', $request->tagsarray);
foreach($tagsArray as $tagInput) {
$tag = new Tag;
$tag->card_id = 'Cant know this yet :(';
$tag->tag = $tagInput;
$tag->save();
}
return redirect('/page');
}
Does someone know how to go about this?
You may try something like this:
$card = new Card([
'card_name' => request()->get('card_name'),
'something_else' => request()->get('something_else')
]);
if($card->save()) {
$tags = [];
// Get the tag information from request
$tagsFromRequest[
['tag_title' => 'A Tag', 'tag_slug' => 'a_tag'],
['tag_title' => 'Another Tag', 'tag_slug' => 'another_tag']
];
foreach($tagsFromRequest as $tag) {
$tags[] = new Tag($tag);
}
$card->tags()->saveMany($tags);
}
Now, prepare your tags from request where each tag item should be an array as given above and I can't be more specific because you gave nothing that you've tried and which might help me to understand your scenario. Check the documentation.

Resources