Dropdown list in Laravel is not displaying - php

Below my drop-down list is not displaying and I don't know where the problem is. Could it be in my SerieController? I want to create an edit/update system but I've had no success.
SerieController
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');
}
Mark Model
class Mark extends Model
{
protected $fillable = ['name_mark'];
public function series()
{
return $this->hasMany('App\Serie', 'fk_mark');
}
}
Serie Model
class Serie extends Model
{
protected $fillable = ['name', 'fk_mark'];
public function marks()
{
return $this->belongsTo('App\Mark', 'fk_mark');
}
}
I have another question. In my view, I have a form. Is the edit ok?
serie.index.blade
<form method="POST" action="{{ route('series.destroy', $serie) }}">
<a class="btn btn-sm btn-warning" href="{{ route('series.edit', $serie->id) }}">Editer</a>
</form>

I think it should be the other way: mark model belongsTo and Series model HasMany, no?

Related

I am trying to relate the restaurant_id with the dishes

I have a one to many relationship between two tables, restaurant and dishes. I cannot associate the restaurant id with the dishes. I had to put the user_id but doing so if the user has more than one restaurant all the dishes would be mixed. so i should replace the user_id with the restaurant_id
DishController
class DishController extends Controller
{
public function index()
{
$dishes = Dish::all();
$restaurant = Restaurant::all();
$dishes = Dish::where('restaurant_id', Auth::id())->get();
return view('admin.dishes.index', compact('dishes', 'restaurant'));
}
public function create()
{
return view('admin.dishes.create');
}
public function store(Request $request, Restaurant $id)
{
$data = $request->all();
$data["restaurant_id"]= Auth::id();
/* $data['slug'] = Str::slug($data['name'], '-'); */
$new_dish = new Dish();
$new_dish->fill($data);
$new_dish->save();
return redirect()->route('admin.dishes.index', $new_dish);
}
public function show($id)
{
$dish = Dish::find($id);
if(!$dish){
abort(404);
}
return view('admin.dishes.show', compact('dish'));
}
public function edit($id)
{
$dish = Dish::find($id);
if (!$dish) {
abort(404);
}
return view('admin.dishes.edit', compact('dish'));
}
public function update(Request $request, Dish $dish)
{
$data = $request->all();
$dish->update($data);
return redirect()->route('admin.dishes.show',$dish);
}
public function destroy($id)
{
//
}
}
Dish model
class Dish extends Model
{
protected $fillable = [
'name', 'ingredients', 'price', 'cover', 'visible','restaurant_id'
];
public function restaurant(){
return $this->belongsTo('App\Restaurant');
}
public function orders(){
return $this->belongsToMany('App\Order');
}
}
You can try by adding a hidden field to restaurant_id in your view form
<input type="hidden" name="restaurant_id" value={{ $restaurant->id }}>
then, in your store method
$restaurant = Restaurant::find($request->restaurant_id);
$restaurant->dishes()->create( //Your Atribbutes here//);

Livewire wire:model not working with nested components

I'm creating a page using livewire to list users from DB and be able to update them..
I have a Users parent component and (User)s child components
users.blade.php:
<div>
#foreach($users as $key => $user)
<livewire:user :user="$user" key="{{$user->id}}">
#endforeach
</div>
user.blade.php
<div>
<form wire:submit.prevent="save">
<input type="text" wire:model="user.name">
<input type="text" wire:model="user.email">
<button class="btn btn-info" type="submit">Save</button>
</form>
</div>
Users.php
class Users extends Component
{
public $users;
public function mount()
{
$this->users = User::all();
}
public function render()
{
return view('livewire.users');
}
}
User.php
class User extends Component
{
public $user;
public function mount(\App\Models\User $user)
{
$this->user = $user;
}
public function render()
{
return view('livewire.user');
}
protected $rules = [
'name' => 'required|min:6',
'email' => 'required|email',
];
public function save()
{
$this->validate();
$user = $this->user;
User::find($user['id'])->fill([
'name' => $user['name'],
'email' => $user['email']
]);
}
}
This is what i'm getting in the browser
Any idea why this is happening ?
I found the issue, it was the validation rules, I had to change it to
protected $rules = [
'user.name' => 'required|min:6',
'user.email' => 'required|email',
];

Delete route not getting any data Laravel 6.X

I tried changing the routes and using a specific name and several things in the action attribute but there is no way the data doesn't appear when I use the form for the delete and the dd() function on my delete route
here is what the dd shows me, no info at all
My routes:
Route::get('/home/Collections', 'CollectionController#index')->name('collection.index');
Route::get('/home/Collections/{Collection}', 'CollectionController#show')->name('collection.show');
Route::get('/home/Collections/{Collection}/edit', 'CollectionController#edit')->name('collection.edit');
Route::put('/home/Collections/{Collection}', 'CollectionController#update')->name('collection.update');
Route::get('/home/Collections/crear', 'CollectionController#create')->name('collection.create');
Route::delete('/home/Collections/{Collection}', 'CollectionController#destroy')->name('collection.destroy');
Route::post('/home/Collections', 'CollectionController#store')->name('collection.store');
My controller:
public function destroy(Collection $collection)
{
$collection->delete();
return redirect('/home'.'/Collections');
}
and my form:
#foreach ($collections as $collection)
<div id="{{$collection->id}}">
<img/>
<p>{{$collection->name}}</p>
<p>{{$collection->description}}</p>
<form action="/home/Collections/{{$collection->id}}" method="POST">
#csrf
#method('DELETE')
<input type="submit" value="ELIMINAR" class = "btn btn-outline-danger mt-2">
</form>
</div>
#endforeach
my collection model:
class Collection extends Model implements Searchable
{
protected $fillable = ['id', 'name', 'description', 'user_id', 'category_id', 'certificate_id', 'img_id'];
public function items()
{
return $this->hasMany(Item::class);
}
public function certificate()
{
return $this->hasOne(Certificate::class);
}
public function image()
{
return $this->hasOne(Image::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function getSearchResult(): SearchResult
{
$url = route('collection.show', $this->id);
return new SearchResult(
$this,
$this->name,
$url
);
}
}
Problem solved a while ago, i forgot to reply to this post.
Solved it changing the Routes URL so they dont match, it seems there was a problem with them even tho it was working like exposed on another project.

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...
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('App\Mark', 'fk_mark');
}
}
Model Mark
class Mark extends Model
{
protected $fillable = ['name_mark'];
public function series(){
return $this->hasMany('App\Serie', 'fk_mark');
}
public function cars(){
return $this->hasMany('App\Car','fk_serie');
}
}
Thank you in advance.
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.
First of all: Which version of Laravel do you use?
Check out route model binding which would compact your functions like this:
public function edit(Serie $serie)
{
$series->load('marks');
return view('admin.series.edit', compact('series'));
}
public function update(Request $request, Serie $serie)
{
$request->validate([
'name' => 'required',
'fk_mark' => 'required'
]);
$series->load('marks');
$series->name = $request->get('name');
$series->fk_mark = $request->get('fk_mark');
$series->save();
return redirect()->route('series.index')
->with('success', 'updated successfully');
}
Further tipps for debugging:
Set 'debug' => true in your app.php
Try to use dd($serie); to see what happens to your model.
Install debugbar: composer require barryvdh/laravel-debugbar --dev
Check your database tables to see if your code successfully created the data.
Write Unit/Feature Test to validate your application logic
Provide more data in your next SO question like sql schema, error messages etc
Without the sql schema and exact problem you're facing it's very hard to debug someone else code. I hope this helps nonetheless.
Edits: grammar, spelling and last sentence fixed/added

Displaying not the id, but the name of a certain data from a table connected with foreign key. - Laravel 5.2

I'm trying to pass data to my view and i want to visualize the name of some records not the id so in my controller I have this:
`public function getIndex() {
return view('admin.rules.list', [
'rules' => ClassSubject::get(),
'classes'=> Clas::lists('name', 'id'),
'subjects' => Subject::lists('name', 'id'),
'teachers'=>User::where('type','=','teacher')->get()->lists('full_name','id')
]);
}
public function postIndex(Request $request) {
$rule = ClassSubject::create([
'class_id'=> $request->get('class_id'),
'subject_id'=> $request->get('subject_id'),
'teacher_id'=> $request->get('teacher_id'),
]);
if($rule->id) {
return redirect()->back()->with('message', [
'type'=> 'success',
'message' => 'Успешно записан нов клас!'
]);
}
return redirect()->back()->with('message', [
'type'=> 'danger',
'message' => 'Класът не е записан!'
]);
}`
I'm passing it in my view like this (part of the table):
`#foreach($rules as $rule)
<tr>
<td>{{ $rule->user->full_name }}</td>
<td>{{ $rule->subject->name}}</td>
<td>{{ $rule->clas->name}}</td>
<td>{{ $rule->created_at->format('d.m.Y, H:i') }}</td>
<td>{{ $rule->updated_at->format('d.m.Y, H:i') }}</td>
<td>
Редактирай
Изтрий
</td>
</tr>
#endforeach`
So this thing: <td>{{ $rule->subject->name}}</td> works perfectly and I see the name of the subject, not the id, but with the other two: <td>{{ $rule->user->full_name }}</td> and <td>{{ $rule->clas->name}}</td>
I have this error msg:
Invalid argument supplied for foreach() (View: C:\xampp\htdocs\school_system\resources\views\admin\rules\list.blade.php)
I'm posting the connection of the tables (models), because I think that may have smthg in common:
User class:
`public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function classes() {
return $this->belongsTo(Clas::class);
}
public function subjects() {
return $this->hasMany(Subject::class);
}
public function classSubject() {
return $this->hasMany(ClassSubject::class);
}
public function studentMark() {
return $this->hasMany(StudentMark::class);
}
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
}`
Clas class:
`protected $fillable = [
'name',
'profile_id'
];
protected $table = 'classes';
public function profile() {
return $this->belongsTo(Profile::class);
}
public function user() {
return $this->hasMany(User::class);
}
public function classSubject() {
return $this->hasMany(ClassSubject::class);
}
public function student() {
return $this->hasMany(Student::class);
}
public function studentMark() {
return $this->hasMany(StudentMark::class);
}`
Subject class:
`protected $fillable = [
'name'
];
public function classSubject() {
return $this->hasMany(ClassSubject::class);
}
public function studentMark() {
return $this->hasMany(StudentMark::class);
}
public function user() {
return $this->belongsTo(User::class);
}
public function teacher() {
return $this->hasMany(Teacher::class);
}`
And the table that connecting them:
`class ClassSubject extends Model
{
protected $fillable = [
'class_id',
'subject_id',
'teacher_id',
'method_of_study_id',
];
public function subject()
{
return $this->belongsTo(Subject::class);
}
public function classes()
{
return $this->belongsTo(Clas::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}`
I would be really thankfull if someone can help, i'm trying to fix this for days.. :)
the first problem I can see is:
$rule->clas->name
there is no clas method on ClassSubject. It should be:
$rule->classes->name
or you can rename the method, as it is not conventional to have a plural name for a "belongsTo" relationship method

Categories