Skip to content
Advertisement

Two models for one Controller in Laravel (methods Edit & Update)

Would you please let me know if this controller SerieController is correct? As I don’t think so. There are two models in fact. One Model is Serie and the other is Mark.

When, I click on the drop down list, I don’t see my items…

enter image description here

public function edit($id)
    {
        $series = Serie::with('marks')->find($id);
        return view('admin.series.edit', compact('series'));
    }



    public function update(Request $request, $id)
    {
        $request->validate([
                'name' => 'required',
                'fk_mark' => 'required'
        ]);
    
        $series = Serie::with('marks')->find($id);
        $series->name = $request->get('name');
        $series->fk_mark = $request->get('fk_mark');
        $series->save();
        return redirect()->route('series.index')
                  ->with('success', 'updated successfully');
    }

My edit.blade.php

<form class="panel-body" action="{{route('series.update',$series->id)}}" method="POST">
<input name="_method" type="hidden" value="PATCH">
@csrf
<fieldset class="form-group">
<label for="form-group-input-1">Name</label>
<input type="text" name="name" class="form-control" id="form-group-input-1" value="{{$series->name}}">
</fieldset>
    
<div class="form-group">
<label for="company-content">Select Mark</label>
<select name="fk_mark" id="" class="form-control">
@foreach($series->marks as $mark)
<option value="{{$mark['id']}}">{{$mark['name_mark']}}</option>
@endforeach
</select>
</div>

Concerning the model

Model Serie

class Serie extends Model
{

    protected $fillable = ['name', 'fk_mark'];

    public function marks(){

        return $this->belongsTo('AppMark', 'fk_mark');
       
    }

}

Model Mark

class Mark extends Model
{

    protected $fillable = ['name_mark'];
    
    public function series(){
        return $this->hasMany('AppSerie', 'fk_mark');
    }

    
    public function cars(){
     return $this->hasMany('AppCar','fk_serie');
   }

}

Thank you in advance.

Advertisement

Answer

In your edit function you have to do this:

public function edit($id)
{
     $series = Serie::with('marks')->find($id);
     return view('admin.series.edit', compact('series'));
}

and in your blade you will fetch the marks like this:

$series->marks->name_mark;

and it is the same method for update function to update two tables data.

I hope it would helpful.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement