dropdown list with several times the same item - php

Below my drop-down list is not displaying correctly 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.
SerielController
public function edit($id)
{
$series = Serie::find($id);
$marks = Mark::find($id);
return view('admin.series.edit', compact('series', 'marks'));
}
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required|string',
'fk_mark' => 'required'
]);
$series = Serie::find($id);
$marks = Mark::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');
}
file series.edit.blade
<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="{{$marks->id}}">
{{$marks->name_mark}}
</option>
#endforeach
</select>
</div>
Model Serie
class Serie extends Model
{
protected $fillable = ['name', 'fk_mark'];
public function marks(){
return $this->belongsTo('App\Mark', 'fk_mark');
}
}
Serie 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 a lot for your help.

In your foreach you made a mistake, the variable should be $mark not $marks
<select name="fk_mark" id="" class="form-control">
#foreach($marks as $mark)
<option value="{{$mark->id}}">
{{$mark->name_mark}}
</option>
#endforeach
</select>
In your edit function you're sending just one Mark to your view, you need to send them all if you want all marks in your select.
public function edit($id)
{
$series = Serie::find($id);
$marks = Mark::all();
return view('admin.series.edit', compact('series', 'marks'));
}

Related

Build update form for an multiselect for an belongstomany relationship laravel

im trying to build an multiselect with laravel in an update form, it should firstly select all what is related to the given id. then should show all the other entries which are not related already.
This is the whole function for the updateControl
public function update(Request $request, Track $track): RedirectResponse
{
//check if data input if yes delete old file and save new one
if ($request->file('track_data')) {
File::delete(public_path('/uploads/tracks/'. $track->getAttribute('data')));
do {
$hashedName = Helper::getRandomString().".".$request->file('track_data')->getClientOriginalExtension();
} while(Track::where(Track::TRACK_DATA, $hashedName)->count());
$request->file('track_data')->storeAs('/uploads/tracks', $hashedName);
$track->setAttribute(Track::TRACK_DATA, $hashedName);
}
//TrackTitle
$track->setAttribute(Track::TRACK_TITLE, $request->get('track_title'));
//TrackDesc
$track->setAttribute(Track::TRACK_DESCRIPTION, $request->get('track_description'));
//checks if topics have input if yes check again if they are already connected if yes throw error if no save the new one
if ($request->input('topics')) {
$track->topics()->detach();
$track->topics()->attach($request->input('topics'));
}
if ($request->input('speakers')){
$track->speakers()->detach();
$track->speakers()->attach('speakers');
}
//checks if moderators have input, if yes check again if they are already connected, if yes throw error - if no save the new one
if ($request->input('moderators')) {
$data = [];
foreach ($request->input('moderators') as $moderatorId) {
$data[$moderatorId] = ['is_moderator' => 1];
};
$track->speakers()->attach($data);
}
//and check write them as moderator in table
$track->update();
return redirect()->route('admin.trackShow');
}
}
This is the Form in my Blade
<form class="d-flex flex-column" action="{{ route('admin.trackUpdate', $track->id) }}" method="post" enctype="multipart/form-data" id="track-form">
#csrf
{{ method_field('patch') }}
#include('errors.alert')
<label for="track_title">Track-Name</label>
<input type="text" name="track_title" id="track_title" value="{{$track->title}}">
<label for="track_description">Track-Description</label>
<input type="text" name="track_description" id="track_description" value="{{ $track->description }}">
<label for="track_data">Track-Data</label>
<input type="file" name="track_data" id="track_data" value="">
<label for="season_id">Seasonauswahl</label>
<select name="season_id" id="season_id">
<option value="{{$track->season()->get()[0]->id}}">Aktuell: {{$track->season()->get()[0]->name}}</option>
#foreach ($seasons as $season)
<option value="{{ $season->id }}">{{ $season->name }}</option>
#endforeach
</select>
<div class="container mt-2">
<label>Topics</label>
<select class="form-select" multiple="multiple" name="topics[]">
#foreach($topics as $topic)
<option value="{{$topic->id}}">{{$topic->name}}</option>
#endforeach
</select>
</div>
<div class="container mt-5">
<label>Moderator</label>
<select class="form-select" multiple="multiple" name="moderators[]">
#foreach($track->speakers()->get() as $moderatorTrack)
#if($moderatorTrack->pivot->is_moderator)
<option selected value="{{$moderatorTrack->id}}">{{$moderatorTrack->getFullName()}}</option>
#else
<option value="{{$moderatorTrack->id}}">{{$moderatorTrack->getFullName()}}</option>
#endif
#endforeach
</select>
</div>
<div class="container mt-5">
<label>Speakers</label>
<select class="form-select" multiple="multiple" name="speakers[]">
#foreach($track->speakers()->get() as $speakerTrack)
#if($speakerTrack->pivot->is_moderator == null)
<option selected value="{{$speakerTrack->id}}">{{$speakerTrack->getFullName()}}</option>
#else
<option value="{{$speakerTrack->id}}">{{$speakerTrack->getFullName()}}</option>
#endif
#endforeach
#foreach($speakers as $speaker)
<option value="{{$speaker->id}}">{{$speaker->getFullName()}}</option>
#endforeach
</select>
</div>
<button type="submit">submit</button>
</form>
</div>
</div>
My Models
TopicModel
class Topic extends Model
{
use HasFactory;
public const TOPIC_NAME = 'name';
protected $fillable = [
self::TOPIC_NAME,
];
/**
* #return BelongsToMany
*/
public function tracks():BelongsToMany
{
return $this->belongsToMany(Track::class, 'topics_tracks', 'topics_id', 'track_id');
}
}
SpeakerModel
class Speaker extends Model
{
use HasFactory;
public const SPEAKER_FIRST_NAME = 'first_name';
public const SPEAKER_LAST_NAME = 'last_name';
public const SPEAKER_IS_MODERATOR = 'is_moderator';
protected $fillable = [
self::SPEAKER_FIRST_NAME,
self::SPEAKER_LAST_NAME,
self::SPEAKER_IS_MODERATOR,
];
/**
* #return BelongsToMany
*/
public function tracks():BelongsToMany
{
return $this->belongsToMany(Track::class, 'speakers_tracks', 'speaker_id', 'track_id')->withPivot('is_moderator');
}
/**
* #return string
*/
public function getFullName() : string
{
return $this->getAttribute(self::SPEAKER_FIRST_NAME) . " " . $this->getAttribute(self::SPEAKER_LAST_NAME);
}
}
TrackModel
class Track extends Model
{
use HasFactory;
public const TRACK_TITLE = 'title';
public const TRACK_DESCRIPTION = 'description';
public const TRACK_SEASON_ID = 'season_id';
public const TRACK_DATA = 'data';
protected $fillable = [
self::TRACK_TITLE,
self::TRACK_DATA,
self::TRACK_DESCRIPTION,
self::TRACK_SEASON_ID,
];
/**
* #return BelongsTo
*/
public function season(): BelongsTo
{
return $this->belongsTo(Season::class);
}
/**
* #return BelongsToMany
*/
public function speakers(): BelongsToMany
{
return $this->belongsToMany(Speaker::class, 'speakers_tracks', 'track_id', 'speaker_id')->withPivot('is_moderator');
}
/**
* #return BelongsToMany
*/
public function topics(): BelongsToMany
{
return $this->belongsToMany(Topic::class, 'topics_tracks', 'track_id', 'topic_id');
}
Thanks for any Help i dont know how to move on!

How do I list my foreign keys in my customer registration view with Laravel?

Is the relationship working in the bank, but I can't show it in my registration view?
Usuario.php
class Usuario extends Model
{
protected $fillable = [
'company',
'name',
'document',
'phone',
'email'
];
public function empresa()
{
return $this->belongsTo('App\Empresa');
}}
Empresa.php
class Empresa extends Model
{
protected $fillable = [
'name',
'uf',
'cnpj'
];
public function usuarios()
{
return $this->hasMany('App\Usuario');
}}
form.blade.php
#foreach($usuarios as $u)
<option value="{{ $u->company_id->name }}">{{ $u->company_id->name }}</option>
#endforeach
UsuarioController.php
class UsuariosController extends Controller
{
public function new(){
$usuarios = Usuario::get();
return view('usuarios.form', ['usuarios' => $usuarios]);
}
enter image description here
please change your empresa() method in Usuario class.
public function empresa()
{
return $this->belongsTo('App\Empresa', 'company');
}
and blade file will be changes like this.
#foreach($usuarios as $u)
<option value="{{ $u->empresa->name }}">{{ $u->empresa->name }}</option>
#endforeach
form.blade.php
#csrf
<div class="form-group">
<label for="exampleInputEmail1">Empresa:</label>
<select name="company" class="form-control">
#foreach($usuarios as $u)
<option value="{{ $u->empresa->name }}">{{ $u->empresa->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Nome:</label>
<input type="text" name="name" class="form-control">
</div>
UsuarioController.
class UsuariosController extends Controller
{
public function index(){
$usuarios = Usuario::get();
return view('usuarios.list', ['usuarios' => $usuarios]);
}
public function new(){
$usuarios = Usuario::get();
return view('usuarios.form', ['usuarios' => $usuarios]);
}
public function adicionar( Request $request ){
$usuario = new Usuario;
$usuarios = Usuario::get();
$usuario = $usuario->create( $request->all() );
return Redirect::to('/usuarios', ['usuarios' => $usuarios]);
}
public function editar( $id ){
$usuario = Usuario::findOrFail( $id );
return view('usuarios.form', ['usuario' => $usuario]);

Laravel insert data to multiple relational tables with a single form

I'm working on Laravel project and i would like to know:
how to insert data to my multiple related tables ?
How can we insert author id in the author_type_id field of the Author table?
How to store author_id in post?
So idon't know how to insert related models using a form. thanks for your help :)
my models
//Post model
class Post extends Model
{
//
protected $fillable = [
'post_type_id','author_id','author_type_id','article'
];
public function posttype()
{
return $this->belongsTo(Posttype::class);
}
public function author()
{
return $this->belongsTo(Author::class);
}
public function authortype()
{
return $this->belongsTo(Authortype::class);
}
}
//Posttype model
class Posttype extends Model
{
//
protected $fillable = [
'post_type'
];
public function posts()
{
return $this->hasMany(Post::class);
}
}
//author model
class Author extends Model
{
//
protected $fillable = [
'author_name','author_first_name','author_type_id'
];
public function posts()
{
return $this->belongsToMany(Post::class);
}
public function authortype()
{
return $this->belongsTo(Authortype::class);
}
}
//Authortype model
class Authortype extends Model
{
//
protected $fillable = [
'author_type '
];
public function author()
{
return $this->hasMany(Author::class);
}
public function posts()
{
return $this->hasMany(Post::class);
}
}
// PostsController Contoller
class PostsController extends Controller
{
public function index()
{
return view('index')->with('posts',Post::all());
}
public function create()
{
return view('create')->with('posttypes',$posttypes)
->with('authors',$authors)
->with('authortypes',$authortypes);
}
public function store(Request $request)
{
$this->validate($request,[
"post_type_id" => "required",
"author_id" => "required",
"author_type_id" => "required",
"article" => "required"
]);
//How can we insert author id in the author_type_id field of the Author table?
$post = Post::create([
"post_type_id" => $request->post_type_id,
"author_id" => $request->author_id,
"author_type_id" => $request->author_type_id,
"article" => $request->article,
]);
return redirect()->back();
}
}
//create post blade
#section('content')
<div class="container">
<form action="{{route('store')}}" method="POST" enctype="multipart/form-data">
{{ csrf_field()}}
<div class="form-group">
<label for="posttype">Post Type</label>
<select class="form-control" id="posttype" name="post_type_id">
#foreach ($posttypes as $posttype)
<option value="{{$posttype->id}}">{{$posttype->post_type}}</option>
#endforeach
</select>
</div>
//author type for author model (author_type_id)
<div class="form-group">
<label for="authortype">Author Type</label>
<select class="form-control" id="authortype" name="author_type_id">
#foreach ($authortypes as $authortype)
<option value="{{$authortype->id}}">{{$authortype->author_type}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="author_name">Author Name</label>
<input type="text" class="form-control" name="author_name" placeholder="your name">
</div>
<div class="form-group">
<label for="author_first_name">Author First Name</label>
<input type="text" class="form-control" name="author_first_name" placeholder="your first name">
</div>
//How to store author_id in post
<div class="form-group">
<label for="content">article</label>
<textarea class="form-control" name="article" rows="8" cols="8"></textarea>
</div>
<button type="submit" class="btn btn-primary">{{__('main.save')}}</button>
</form>
</div>
#endsection
I found solution, May this can help you in future.
$author = Author::create([
'author_type_id' => $request->author_id,
]);
$post = Post::create([
"post_type_id" => $request->post_type_id,
"author_id" => $author->id,
"author_type_id" => $request->author_type_id,
"article" => $request->article,
]);
Auther::create([
'author_type_id' => $request->author_id,
]);

Problem with Laravel scope in search form

I have search form that searches ads/properties through certain filters. I have problem when I use 'like' function my search fields for property id and user id don't work properly. For example when I put 1 in property id and submit form it returns all properties that have number 1 in their id (for example 1, 11, 21, 111). And when I change my code to be without 'like' function and just 'where' function it returns correct results, but then other filters don't work. Any help is appreciated. Here is my code.
Property.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Property extends Model
{
protected $guarded = ['id'];
public function scopeId($query, $id)
{
return $query->where('id', $id);
}
public function scopeUserId($query, $user_id)
{
return $query->where('user_id', 'like', '%'.$user_id.'%');
}
public function scopeTitle($query, $title)
{
return $query->where('title', 'like', '%'.$title.'%');
}
public function scopeDescription($query, $description)
{
return $query->where('description', 'like', '%'.$description.'%');
}
public function scopeActive($query, $active)
{
return $query->where('active', 'like', '%'.$active.'%');
}
public function scopeViews($query, $views)
{
return $query->where('page_views', 'like', '%'.$views.'%');
}
}
PropertyController.php
class PropertyController extends Controller
{
public function show(Request $request)
{
$properties = Property::id($request->id)
->userId($request->user_id)
->title($request->title)
->active($request->active)
->views($request->views)
->description($request->description)
->paginate(10);
return view('admin.properties.propertylist', compact('properties','request'));
}
}
propertylist.blade.php
<form action="{{route('admin.property')}}" method="get">
<label for="id">Id</label>
<input type="number" name="id" id="id" value="#if(!empty($request->id)){{$request->id}}#endif">
<label for="user_id">User id</label>
<input type="number" name="user_id" id="user_id" value="#if(!empty($request->user_id)){{$request->user_id}}#endif">
<label for="title">Title</label>
<input type="text" name="title" id="title" value="#if(!empty($request->title)){{$request->title}}#endif">
<label for="description">Description</label>
<input type="text" name="description" id="description" value="#if(!empty($request->description)){{$request->description}}#endif">
<label for="active">Status</label>
<select name="active"id="active">
<option value='' #if(empty($request->active))selected #endif>All</option>
<option value="A" #if(!empty($request->active) && $request->active == 'A')selected #endif>Approved</option>
<option value="Q" #if(!empty($request->active) && $request->active == 'Q')selected #endif>Queued</option>
<option value="S" #if(!empty($request->active) && $request->active == 'S')selected #endif>Suspicious</option>
<option value="D" #if(!empty($request->active) && $request->active == 'D')selected #endif>Denied</option>
</select>
<label for="views">Views</label>
<input type="text" name="views" id="views" value="#if(!empty($request->views)){{$request->views}}#endif">
<button class="btn btn-default" type="submit"> Submit </button>
</form>

DropDown list for foreign key

I would like to learn to create a dropdown list with a foreign key on Laravel.
For information, I have a table named series with 3 fields id, name, fk_mark.
Then, I have another table named marks with 2 fields id, name_mark.
My create works correctly, here is the proof.
I am stuck about the dropdownlist, what is the syntax please for my foreign key ?
<fieldset class="form-group">
<label for="form-group-input-1">Name serie</label>
<input type="text" name="name" class="form-control" id="form-group-input-1">
</fieldset>
<fieldset class="form-group">
<label for="form-group-input-1">FK Mark</label>
<input type="text" name="fk_mark" class="form-control" id="form-group-input-1">
</fieldset>
I have tried this but without result...
<div class="form-group">
<label for="company-content">Select compagny</label>
<select name="fk_mark" class="form-control">
#foreach($series as $serie)
<option value="{{$serie->id}}"> {{$serie->name}} </option>
#endforeach
</select>
</div>
Here is my Models
Model Mark
class Mark extends Model
{
protected $fillable = ['name_mark'];
public function series(){
return $this->hasMany('App\Serie', 'fk_mark');
}
}
Model Serie
class Serie extends Model
{
protected $fillable = ['name', 'fk_mark'];
public function marks(){
return $this->belongsTo('App\Mark', 'fk_mark');
}
}
SerieController
public function index()
{
$series = Serie::oldest()->paginate(5);
return view('admin.series.index', compact('series'))
->with('i', (request()->input('page', 1)-1)*5);
}
public function create()
{
return view('admin.series.create');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'fk_mark' => 'required'
]);
Serie::create($request->all());
return redirect()->route('series.index')
->with('success', 'save');
}
Thank you very much for your help.

Categories