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.
Related
I have a model named Articles which contained three attributes: 'title', 'subtitle' and 'body' and it worked perfectly but after adding four columns to that model ('subtitle2', 'body2', 'subtitle3' and 'body3') the newly added columns stay NULL after creating articles.
There is clearly something that I missed but I can't figure out what.
This is the migration:
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->string('subtitle2')->nullable()->default(null);
$table->text('body2')->nullable()->default(null);
$table->string('subtitle3')->nullable()->default(null);
$table->text('body3')->nullable()->default(null);
});
}
After migrating I edited my app/Http/Models/Article.php and it looks like this:
protected $fillable = [
'title',
'subtitle',
'body',
'subtitle2',
'body2',
'subtitle3',
'body3',
];
This is my app/Http/Livewire/CreateArticle.php
class CreateArticle extends Component
{
use WithFileUploads;
public $title;
public $subtitle;
public $body;
public $category;
public $subtitle2;
public $body2;
public $subtitle3;
public $body3;
public $temporary_images;
public $images = [];
public $article;
public function store()
{
$this->validate();
$this->article = Category::find($this->category)->articles()->create($this->validate());
$this->article->user()->associate(Auth::user());
$this->article->save();
if(count($this->images)){
foreach($this->images as $image){
$newImage = $this->article->images()->create(['path'=>$image->store('images', 'public')]);
dispatch(new ResizeImage($newImage->path, 600, 400));
}
}
}
And finally I added these lines to the form:
{{-- INSERT SUBTITLE 2 --}}
<div class="mb-3">
<label for="subtitle2" class="form-label">Second paragraph subtitle</label>
<input type="text" wire:model="subtitle2" class="form-control" id="subtitle2">
</div>
{{-- INSERT PARAGRAPH 2 --}}
<div class="mb-3">
<label for="body2" class="form-label">Second paragraph</label><br>
<textarea class="form-control" wire:model="body2" id="body2" cols="30" rows="3"></textarea>
</div>
{{-- INSERT SUBTITLE 3 --}}
<div class="mb-3">
<label for="subtitle3" class="form-label">Third paragraph subtitle</label>
<input type="text" wire:model="subtitle3" class="form-control" id="subtitle3">
</div>
{{-- INSERT PARAGRAPH 3 --}}
<div class="mb-3">
<label for="body3" class="form-label">Third paragraph</label><br>
<textarea class="form-control" wire:model="body3" id="body3" cols="30" rows="3"></textarea>
</div>
dd($this); is returning the following
Tinker is showing all columns
You need to specify
protected $rules
in order to use
$this->validate()
Assuming the dd(); image you provided is the latest. I can see the new columns does not exists in database. ('subtitle2', 'body2', 'subtitle3' and 'body3') all these are not available in list.
so I think you are missing to run the migrate command
php artisan migrate
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,
]);
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'));
}
I have 4 fields which are id, name, prenom, date_naissance.
When I insert a recording in my phymyadmin, I don't have a problem with the date_naissance.
However, when I try to insert a date_naissance in my insert form, I have an error message.
SQLSTATE[HY000]: General error: 1364 Field 'date_naissance' doesn't
have a default value (SQL: insert into eleves (nom, prenom,
updated_at, created_at) values (Benoit, Piret, 2019-03-07
22:31:24, 2019-03-07 22:31:24))
Do you see the problem ?
public function create()
{
return view('admin.eleves.create', compact('eleves'));
}
public function store(Request $request)
{
$request->validate([
'nom' => 'required|string',
'prenom' => 'required|string',
'date_naissance' => 'required|date'
]);
Eleve::create($request->all());
return redirect()->route('eleves.index')
->with('success', 'save');
}
My View create
<form class="panel-body" action="{{route('eleves.store')}}" method="POST">
#csrf
<fieldset class="form-group">
<label for="form-group-input-1">Nom</label>
<input type="text" name="nom" class="form-control" id="form-group-input-1">
</fieldset>
<fieldset class="form-group">
<label for="form-group-input-1">Prénom</label>
<input type="text" name="prenom" class="form-control" id="form-group-input-1">
</fieldset>
<fieldset class="form-group">
<label for="form-group-input-1">Date naissance</label>
<input type="date" name="date_naissance" class="form-control" id="form-group-input-1">
</fieldset>
Back
<button type="submit" class="btn btn-sm btn-primary">Valider</button>
</form>
Model:
class Eleve extends Model
{
//
protected $fillable = ['nom', 'prenom'];
protected $dates = ['date_naissance'];
In your Model
class Eleve extends Model
{
//
protected $fillable = ['nom', 'prenom','date_naissance']; // missing date_naissance here.
protected $dates = ['date_naissance'];
You will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment by default.
Fillable you specify which fields are mass-assignable in your model, you can do it by adding the special variable $fillable to the model. So in the model you need to add also date_naissance:
class Eleve extends Model {
protected $fillable = ['nom', 'prenom','date_naissance']; //only the field names inside the array can be mass-assign
protected $dates = ['date_naissance'];
}
More details: you can easily understand here What does “Mass Assignment” mean in Laravel
I'm building API and I'm struggling with store data for multiple employee roles, how to store, could you provide me some example,
sorry for using the foreign language.
Karyawan=employee,
Jabatan=role
Karyawan.php
public function jabatan() {
return $this->hasMany('\App\Jabatan','id_jabatan');
}
Jabatan.php
public function karyawan(){
return $this->belongsTo('\App\Karyawan','id_jabatan');
}
how to KaryawanController at store function should be...
this is my model and controller
i created my pivot table and i got this error
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into tb_jabatan_karyawan (id_jabatan, id_karyawan, 0, 1) values (0, 57, 1, 2))
ini controller sama modelnya..
I am using User and Role instead of Karyawan and Jabatan respectively (sorry for that). User and Role has Many-to-Many relation because one User may have multiple Roles and vice versa.
roles Table
+----+------+-----------+
| id | role | timeStamps|
+----+------+-----------+
role_user Pivot Table
+----+---------+---------+
| id | user_id | role_id |
+----+---------+---------+
Role Model
public function users(){
return $this->belongsToMany('App\User');
}
User Model
public function roles(){
return $this->belongsToMany('App\Role');
}
RoleUser Pivot
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class RoleUser extends Pivot
{
protected $table='role_user';
protected $fillable = [
'user_id','role_id'
];
public static $role_attach_rules = [
'roles' => 'required|array|min:1|exists:roles,id'
];
public function user(){
return $this->hasOne('App\User', 'id', 'user_id');
}
public function role(){
return $this->hasOne('App\Role', 'id', 'user_id');
}
}
Controller Code for Assigning Roles to the User
Here you will understand the methods by their names.
public function getAssignRole(){
$users = User::all();
$roles=Role::all();
return View::make('assignrole', compact('users', 'roles'));
}
public function postAssignRole(Request $request){
$attachvalidator = Validator::make($request->all(),RoleUser::$role_attach_rules);
if ($attachvalidator->fails()){
return Redirect::back()->withErrors($attachvalidator)->withInput();
}
$user=$request->get('user');
$role=$request->get('roles');
$attach = User::find($user)->roles()->attach($role);
return 'Success';
}
public function detachRole(Request $request){
$user=$request->get('user_update');
$role=$request->get('roles_update');
$attach = User::find($user)->roles()->detach($role);
return 'detach Success';
}
View file (assignrole.blade.php) for Assigning Roles
//This form is for assigning roles
<form method="post" action="{{route('role.assignrole.post')}}">
{{csrf_field()}}
<select id="user" name="user" class="select_with_style" required>
#foreach($users as $user)
<option value="{{$user['id']}}">{{$user['name']}}</option>
#endforeach
</select>
<select id="roles" name="roles[]" class="select_with_style" multiple="" required>
#foreach($roles as $role)
<option value="{{$role['id']}}">{{$role['role']}}</option>
#endforeach
</select>
<br>
<input type="submit" name="submit" class="submit action-button" value="Submit"/>
</form>
//This is for detaching roles from user
<form method="post" action="{{route('role.detach')}}">
{{csrf_field()}}
<select id="user_update" name="user_update" class="select_with_style" required>
#foreach($users as $user)
<option value="{{$user['id']}}">{{$user['name']}}</option>
#endforeach
</select>
<select id="roles_update" name="roles_update[]" class="select_with_style" multiple="" required>
#foreach($roles as $role)
<option value="{{$role['id']}}">{{$role['role']}}</option>
#endforeach
</select>
<br>
<input type="submit" name="submit" class="submit action-button" value="Update"/>
</form>
Routes
Route::get('role/assignrole', array('as' => 'role.assignrole', 'uses' => 'YourController#getAssignRole'));
Route::post('role/assignrole', array('as' => 'role.assignrole.post', 'uses' => 'YourController#postAssignrole'));
Route::post('role/detach', array('as' => 'role.detach', 'uses' => 'YourController#detachRole'));
Hope this helps.
Edit
You can use Voyager instead of doing this much work. It is very easy to understand and well structured and I think you will love it.