Laravel - Store data with a Polymorphic relation - php

I'm new to Laravel and would I'm confused on how to properly store a data from a form with a polymorphic relation. I have three models.
Salary Grade Model
public function salaryallowance() {
return $this->morphOne('App\SalaryAllowanceModel', 'salary');
}
Salary Matrix Model
public function salaryallowance() {
return $this->morphOne('App\SalaryAllowanceModel', 'salary');
}
Salary Allowance Model
public function salary() {
return $this->morphTo();
}
Salary Allowance Controller
public function create()
{
$getSalaryAllowanceWithSalary = SalaryAllowanceModel::all();
$getPosition = PositionModel::pluck('position_name', 'id');
$getSalaryGrade = SalaryGradeModel::pluck('salary_grade', 'id');
return view('SalaryAllowanceView.add', compact('getSalaryAllowanceWithSalary', 'getPosition', 'getSalaryGrade'));
}
public function store(Request $request) {
SalaryAllowanceModel::create ([
'salary_id' => $request->position,
'salary_type' => get_class($request),
'salary_allowance' => $request->allowance,
'salary_transportation' => $request->transportation,
'salary_medical' => $request->medical,
'salary_education' => $request->education,
'salary_housing' => $request->housing,
'salary_clothing' => $request->clothing
]);
return back();
}
Blade.php
<div class="form-group col-md-12 row">
<label class="col-md-4 col-form-label text-md-right">{{ __('Position') }}</label>
<div class="col-md-6">
<select name="position" class="form-control">
<option value="0">Please Select Position</option>
#foreach ($getPosition as $id => $position)
<option value="{{$id}}">{{ $position }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group col-md-12 row">
<label class="col-md-4 col-form-label text-md-right">{{ __('Allowance') }}</label>
<div class="col-md-6">
<input type="text" class="form-control" name="allowance">
</div>
</div>
I'm having a hard time to do a syntax for storing the data. I want the ID to be based on the selected drop-down.
EDIT:
I have tried using this approach but I'm getting the wrong ID to be saved in the column salary_id of Salary Allowance table. The model is properly saved in the salary_type.
public function store(Request $request)
{
$post = SectionModel::find(2);
$comment = new SalaryAllowanceModel;
$comment->salary_allowance = $request->allowance;
$comment->salary_id = $request->position;
$post->salaryallowance()->save($comment);
return back();
}
EDIT 2: SOLVED Finally I have found the solution. Posting answer for people who have the same problem
public function store(Request $request)
{
$post = SalaryMatrixModel::find($request->position);
$comment = new SalaryAllowanceModel;
$comment->salary_allowance = $request->allowance;
$comment->salary_id = $request->position;
$post->salaryallowance()->save($comment);
}

Related

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

dropdown list with several times the same item

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

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.

To POST an input using helpers

i'm totally new to laravel. i'm trying to POST an input from another table but in same database using Helpers. I try to get name by email using Helpers. But i got this error:
Trying to get property 'name' of non-object (View: C:\xampp\htdocs\ims\resources\views\leave\add.blade.php)
Below is my Helpers:
public static function getnamebyemail($id)
{
$userdata = DB::table('hr_intern_table')->where('id', '=', $id)->first();
if(!empty($userdata))
{
return $userdata->name;
}
return '';
}
Below is the form that i try to get and post:
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<div class="form-group form-float">
<label for="name" class="form-label">Trainee Name</label>
<div class="form-line">
<input type="text" class="form-control" name="name" disabled value="{{Helpers::getnamebyemail($data->name)}}"/>
</div>
</div>
</div>
Below is my controller:
public function add($id)
{
$data = DB::table('leave_req_tb')->where('id', '=', $id)->first();
return view('leave.add', compact('data', 'id'));
}
public function store_request(Request $request, $id)
{
$data = $this->validate($request, [
'leave_applied'=>'required',
'start_leave'=>'required',
'end_leave'=>'required',
'justification'=>'required',
'sv_approval'=>'required',
'hod_approval'=>'required',
'hr_approval'=>'required',
]);
DB::table('leave_req_tb')->where('id', '=', $id)->insert([
'intern_id'=>$intern_id,
'leave_applied'=>$request->leave_applied,
'start_leave'=>$request->start_leave,
'end_leave'=>$request->end_leave,
'justification'=>$request->justification,
'sv_approval'=>$request->sv_approval,
'hod_approval'=>$request->hod_approval,
'hr_approval'=>$request->hr_approval,
'created_at' => now(),
]);
return redirect('/leave/view')->with('success', 'The profile has been updated successfully.');
}
I appreciate if someone can help me and explain why i got this error because i don't think there is a problem with my code.
Helper functions are global and don't have a class
So in your Helpers.php
Just place the
function getnamebyemail($id)
{
$userdata = DB::table('hr_intern_table')->where('id', '=', $id)->first();
if(!empty($userdata))
{
return $userdata->name;
}
return '';
}
along with the required imports
In your blade just use
{{getnamebyemail($data->name)}}

Form array validation Laravel 5.2

I am currently stuck on solving this problem. I am new to Laravel and the MVC framework. I am struggling to create the dynamic form that gives the user the ability to add as many forms as possible. When the user enters the page at first it generates 5 form fields . Here is a look at my code so far.
<div id ={{$id = "from".$i}} >
<div class="form-group col-md-6">
<div class="col-md-6 form-group">
<label for={{$id = "Address".$i}}>Address</label>
<input type="text" name = "address[{{$i}}]" class="form-control" id={{$id = "Address".$i}} placeholder="Street Address"> <!-- problem form array how does this work in laravel -->
</div>
<div class="form-group col-md-6">
<label for={{$id = "city".$i}}>City</label>
<input type="text" value = "{{ old('city') }}" class="form-control" id={{$id = "City".$i}} placeholder="City">
#if ($errors->has('city'))
<span class="help-block">
<strong>{{ $errors->first('city') }}</strong>
</span>
#endif
</div>
How would I go about validating a form in Laravel 5.2 with from array
here's my controller
public function Postdata(Request $request) {
$this->validate($request->all(), [
'address.*' => 'required|string',
'city' => 'required',
]);
}
I am using a for loop to generate the forms dynamically.
here is the error I get
ErrorException in ValidatesRequests.php line 49:
Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request, array given, called in
C:\wamp\www\Dynamic- 1.0\app\Http\Controllers\propContoller.php on line 34 and defined
Can someone please help or point me in the right direction thank you !
add name="city[{{$i}}]"
Create a specific request with php artisan make:request PostRequest
Change public function Postdata(Request $request) { to public function Postdata(PostRequest $request) {
Remove the validate function call from your controller
Go to /app/Http/Requests/PostRequest.php
Then edit the rules function to something like this ...
.
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [];
foreach($this->request->get() as $key => $val)
{
$rules['address.' . $key] = 'required';
$rules['city.' . $key] = 'required';
}
return $rules;
}
Thank You man ! this is the solution I end up with
<div class="form-group col-md-6">
<div class="col-md-6 form-group">
<label for={{$id = "Address".$i}}>Address</label>
<input type="text" name="address[{{$i}}]" class="form-control" id={{$id = "Address".$i}} placeholder="Street Address">
</div>
in post request i did this
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules() {
$rules = [];
foreach($this->request->get('address') as $key => $val) {
$rules['address.'.$key] = 'required';
}
return $rules;
}

Categories