Livewire multi select form data - php

I'm using laravel 8 and needs to get data selected from a form selected data and insert only Clinic_id and Service_id on my ServClinic table
here is my models
needs to save data from a many to many relationship and get data further
my Clinic Model
<?php
class Clinic extends Model
{
use HasFactory;
protected $table = "clinics";
public function services(){
return $this->belongsToMany(ServiceData::class,'serv_clinics');
}
}
and
My serviceData Model
<?php
class ServiceData extends Model
{
use HasFactory;
protected $tabel = "service_data";
public function clinic(){
return $this->belongsToMany(Clinic::class,'serv_clinics');
}
}
and
ServeClinic Model
<?php
class ServClinic extends Model
{
use HasFactory;
protected $tabel ="serv_clinics";
}
and view is
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-4 pb-2 mb-3 border-bottom">
<h1 class="h2">اضافة خدمة بالعيادة</h1>
</div>
#if(Session::has('message'))
<div class="alert alert-success" role="alert">{{Session::get('message')}}</div>
#endif
<form class="form-horizontal" wire:submit.prevent="storeServices">
<div class="form-group">
<label class="col-md-4 control-label">اختار العيادة</label><br/>
<div class="col-md-4" wire:ignore>
<select class="sel_categories form-control" name="clinics[]">
#foreach($clinics as $clinic)
<option value="{{$clinic->id}}">{{$clinic->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">اختارالخدمات</label><br/>
<div class="col-md-4" wire:ignore>
<select class="form-control" name="services[]" multiple="multiple">
#foreach($services as $service)
<option value="{{$service->id}}">{{$service->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-4">
<button type="submit" class="btn btn-primary">حفظ</button>
</div>
</div>
</form>
</main>
needs to get clinic_id and serve_id and save it in ServClinic table
my migration file is
public function up()
{
Schema::create('serv_clinics', function (Blueprint $table) {
$table->id();
$table->bigInteger('clinic_id')->unsigned();
$table->bigInteger('serve_id')->unsigned();
$table->timestamps();
$table->foreign('clinic_id')->references('id')->on('clinics')->onDelete('cascade');
$table->foreign('serve_id')->references('id')->on('service_data')->onDelete('cascade');
});
}

If you are in selec2 multiples element, I think you first must get this data and get the collection of clinic models to be attached to services
public $clinics = []; // or whatever is the property for clinics ids array
public $services = []; // property of serviceData ids array
public function storeServices()
{
$clinicCollection = Clinic::whereIn('id',$clinics)->get();
foreach($clinicCollection as $clinic) {
$clinic->attach($services);
}
}
if you follow the Laravel docs about the many-many intermediate table (https://laravel.com/docs/8.x/eloquent-relationships#many-to-many) you will see don't need the ServClinics model. Only create the migration for clinic_service_data intermediate table.
Of course, this is the simplest way for my point. Now, if you go on with your solution, then you can do it like:
public function storeServices()
{
$clinicCollection = Clinic::whereIn('id',$clinics)->get();
$servDataCollection = Servicedata::whereIn('id',$services)->get();
foreach($clinicCollection as $clinic) {
foreach($servDataCollection as $servData) {
ServClinic::create([
'clinic_id' => $clinic->id,
'serve_id' => $servData->id
]);
}
}
}
And of course, instead foreach statements you can filter the collections

Related

Updating/Adding value to array in Laravel 8

I am new developer, and I seem to be stuck on handling arrays in laravel. I am using Laravel 8, and I cant seem to solve this situation.
I am building an internal recruitment site, where once a manager posts a job, employees will be able to apply to those specific jobs. I have defined the table in the database to have the "applicants" as an array consisting of the user_id's. However, I seem to not be able to add more than one array to it.
Below is my Recruitment Model
class Recruitment extends Model
{
use HasFactory;
protected $fillable = [
'title',
'salary',
'term_start',
'term_end',
'deadline',
'details',
'status',
'applicants',
];
public function user(){
return $this->belongsTo("\App\Models\User");
}
protected $casts = [
'applicants' => 'array'
];
}
Next is my migration (I am using text format, because the DB on the server is older and does not support json)
public function up()
{
Schema::create('recruitments', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->decimal('salary', 10, 2);
$table->date('term_start');
$table->date('term_end');
$table->date('deadline');
$table->longText('details');
$table->string('status');
$table->text('applicants')->nullable();
$table->timestamps();
});
}
Here is my blade
<div class="container">
<div class="row">
<div class="card col-sm-12 py-3">
<div class="card-header border d-flex justify-content-between align-items-center">
<h3 class="w-75">{{ $job->title }}</h3>
<div class="w-25">
<p class="my-0 my-0">Created at: <span class="text-info">{{ $job->created_at }}</span></p>
<p class="my-0 my-0">Last updated at: <span class="text-primary">{{ $job->updated_at }}</span></p>
</div>
</div>
<div class="card-body">
// display job details here
<form action="{{ route('add-applicant', ['id' => $job->id ]) }}" method="POST" class="col-sm-12 d-flex justify-content-center align-items-center">
#csrf
<input type="text" name="user_id" id="user_id" value="{{ Auth::user()->id }}" hidden>
<button type="submit" class="btn btn-success w-25">Apply</button>
</form>
</div>
</div>
</div>
</div>
and lastly my controller
public function addApplicant($id, Request $reqst){
$job = Recruitment::find($id);
$user[] = $reqst->user_id;
$job->applicants = $user;
$job->save();
return redirect()->back();
}
While this controller will be able to save an array, it unfortunately overwrites the already existing one (let's say a second user applied). When I try to use an array_push, it does nothing, and I still end up with just one value in the array.
Sorry this was a bit of a read, but I appreciate any help I cen get with this. Thanks
Try in
public function addApplicant($id, Request $reqst){
$job = Recruitment::find($id);
$job->applicants = $reqst->user_id;
$job->save();
return redirect()->back();
}
and in Recruitment model should have
public function user()
{
return $this->belongsTo(User::class, 'applicants');
}
and migration file
$table->integer('applicants')->nullable();

SQLSTATE[23000]:Integrity constraint violation: 1048 Column 'giorno_raccolta_id' cannot be null

Calendar
I'm developing an app with Laravel 8 to show the weekly calendar of separate waste collection, but when I go to press the add day button I have the following error: SQLSTATE [23000]: Integrity constraint violation: 1048 Column 'giorno_raccolta_id' cannot be null (SQL: insert into notes ( collection_day_id, start_time, end_time, updated_at, created_at) values (?,?,?, 2021-05-28 12:48:04, 2021- 05-28 12:48:04))
Form.blade.php
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">Giorno</label>
<select name="giorno" class="form-select" id="inputGroupSelect01">
#foreach ($days as $day)
<option value="{{$day->id}}" {{$note->giorno_id == $day->id ? 'selected' : ''}} >{{$day->giorno}}</option>
#endforeach
</select>
</div>
#if($errors->has('giorno'))
<div class="alert alert-danger" role="alert">
{{ $errors->first('giorno')}}
</div>
#endif
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">Tipologia</label>
<select name="tipologia" class="form-select" id="inputGroupSelect01">
#foreach ($categories as $c)
<option value="{{$c->id}}" {{$note->tipologia_id == $c->id ? 'selected' : ''}} >{{$c->categoria}}</option>
#endforeach
</select>
</div>
#if($errors->has('tipologia'))
<div class="alert alert-danger" role="alert">
{{ $errors->first('tipologia')}}
</div>
#endif
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">Giorno raccolta</label>
<select name="giorno_raccolta_id" class="form-select" id="inputGroupSelect01">
#foreach ($days as $day)
<option value="{{$day->id}}" {{$note->giorno_raccolta_id == $day->id ? 'selected' : ''}} >{{$day->giorno}}</option>
#endforeach
</select>
</div>
#if($errors->has('giorno_raccolta_id'))
<div class="alert alert-danger" role="alert">
{{ $errors->first('giorno_raccolta_id')}}
</div>
#endif
<div class="input-group mb-3">
<label class="input-group-text">Ora inizio</label>
<input type="time" name="ora_inizio">
</div>
#if($errors->has('ora_inizio'))
<div class="alert alert-danger" role="alert">
{{ $errors->first('ora_inizio')}}
</div>
#endif
<div class="input-group mb-3">
<label class="input-group-text">Ora fine</label>
<input type="time" name="ora_fine">
</div>
#if($errors->has('ora_fine'))
<div class="alert alert-danger" role="alert">
{{ $errors->first('ora_fine')}}
</div>
#endif
#csrf
2.Table Notes
public function up()
{
Schema::create('notes', function (Blueprint $table) {
$table->increments('id')->start_from(1);
$table->unsignedInteger('giorno_id');
$table->unsignedInteger('tipologia_id');
$table->unsignedInteger('giorno_raccolta_id');
$table->time('ora_inizio');
$table->time('ora_fine');
$table->timestamps();
});
}
3.WeekController
<?php
namespace App\Http\Controllers;
use App\Models\note;
use App\Models\Day;
use Illuminate\Http\Request;
class WeekController extends Controller
{
public function index(){
$notes = note::all();
return view('calendar.index',
compact('notes'));
}
public function create(){
$days = Day::all();
$categories = Category::all();
$notes = new note();
return view('calendar.create',
compact('days', 'categories', 'notes'));
}
public function store(){
note::create($this->validateRequest());
return redirect()->route('calendar.index');
}
public function show(note $note){
$note = note::find($note)->first();
return view('calendar.show',compact('note'));
}
public function edit(note $note){
$days = Day::all();
return view('calendar.edit',compact('note','days'));
}
public function update(note $note){
$note ->update($this->validateRequest());
return redirect()->route('calendar.show',$note->id);
}
public function destroy(note $notes){
$notes->delete();
return redirect()->route('calendar.index');
}
private function validateRequest(){
return request()->validate([
'giorno_id' => 'required|unique:notes',
'tipologia' => 'required',
'giorno_raccolta' => 'required',
'ora_inizio' => 'required',
'ora_fine' => 'required'
]);
}
}
I also have another problem, when I go to save the data in the database nothing is saved.
Can you help me troubleshoot the app.
The days and types of refusals I recover from two other tables:
Days Table
public function up()
{
Schema::create('days', function (Blueprint $table) {
$table->id();
$table->string('giorno');
$table->timestamps();
});
}
2.Categories table
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('categoria');
$table->timestamps();
});
}
Note Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Day;
class note extends Model
{
use HasFactory;
protected $fillable = [];
protected $guarded = ['id'];
public function days(){
return $this->hasOne(Day::class);
}
}
Day model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\note;
use App\Models\Category;
class Day extends Model
{
use HasFactory;
public function notes(){
return $this->hasOne(note::class);
}
public function category(){
return $this->belongsTo(category::class);
}
}
Category model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Model\Day;
class Category extends Model
{
use HasFactory;
public function days(){
return $this->hasMany(Day::class);
}
}
I suggest you make $fillable and pass it the attributes you want to make mass assignable https://laravel.com/docs/8.x/eloquent#mass-assignment. In the other hand, I see that all your select elements has the same id, since DOM id element must be unique. And finally, check on the create method the $request received data
....(Request $request)
{
dd($request)
}

How I use relationship in blade template (hasOne) || Laravel

Okay i'm trying get "likes" and "users" in Posts by relationship hasOne.
here is my Post.php Model
class Posts extends Model
{
protected $table = 'posts';
public function User()
{
return $this->hasOne(User::class, 'id', 'user_id');
}
public function Like()
{
return $this->hasOne(Like::class, 'post_id', 'id');
}}
My Blade template
#foreach ($showdeals as $deal)
<div class="tab-pane active" id="home" role="tabpanel">
<div class="card-body">
<div class="profiletimeline">
{{$deal->like->status}}
<br>
{{$deal->user->email}}
<div class="sl-item">
<div class="sl-left"> <img src=" {{asset( '/assets/images/users/2.jpg')}}" alt="user" class="img-circle"> </div>
<div class="sl-right">
<div> {{$deal->user->username}} || {{$deal->subject}} <Br> <span class="sl-date">{{$deal->created_at}}</span>
<div class="m-t-20 row">
<div class="col-md-3 col-xs-12"><img src="{{$deal->image}}" alt="user" class="img-responsive radius"></div>
<div class="col-md-9 col-xs-12">
<p> {{$deal->body}} </p> עבור למוצר </div>
</div>
<div class="like-comm m-t-20"> 2 תגובות <i class="fa fa-heart text-danger"></i> 5 לייקים </div>
</div>
</div>
</div>
</div>
<hr></div>
</div>
#endforeach
And there is my Controller
class PostsController extends Controller
{
public function showdeals()
{
$showdeals = Posts::with( 'User', 'Like')->get();
return view('posts.show', compact('showdeals'));
}
public function helpnewview(){
return view('posts.anew');
}
public function helpnew(Request $request){
//User pick link
$userlink = $request['userlink'];
return \Redirect::route('newdeal', compact('userlink'));
}
public function new(Request $request)
{
//Emdeb user link
$link = Embed::create($request['userlink']);
$linke = $request['userlink'];
return view('posts.new', compact('link', 'userlink', 'linke'));
}
public function create(Request $request)
{
$posts = New Posts;
$posts->user_id = Auth::User()->id;
$posts->subject = $request['subject'];
$posts->body = $request['body'];
$posts->link = $request['link'];
$posts->price = $request['price'];
$posts->image = $request['image'];
$posts->tag = $request['tag'];
$posts->save();
return back();
}
}
Now if I do something like {{$deal->user->email}} its will work,
if I go to something like this {{$deal->like->status}} its does not work,
am I missing something ?
If you want multiple relationships to be eagerly loaded you need to use an array of relationships: Model::with(['rl1', 'rl2'])->get();
public function showdeals()
{
...
$showdeals = Posts::with(['User', 'Like'])->get();
...
}
EDIT:
From that json in the comments that I see, there is no attribute named status in your Like model so thats probably the root of the problem
Controller edit this code
public function showdeals()
{
$showdeals = Posts::all();
return view('posts.show', compact('showdeals'));
}
And blade file code
#foreach ($showdeals as $deal)
<div class="tab-pane active" id="home" role="tabpanel">
<div class="card-body">
<div class="profiletimeline">
{{ $deal->Like->status }}
<br>
{{ $deal->User->email }}
#endforeach
I think everything is good except
{{$deal->like->status}} {{$deal->user->email}}
Please try as
{{$deal->Like()->status}}
<br>
{{$deal->User()->email}}

Laravel - Getting all records not just the first and putting together?

I have tried asking this question to everyone but nobody can see why I am trying to do it or why its not working but I will try my best to explain it properly this time.
I have a simple government page on my website that shows 3 panels in bootstrap with Higher Government, Senior Ministers and Junior Ministers. Inside each of them panels it shows a list of accounts assigned to that government rank.
Here is my government.blade.php:
#include('frontend.header')
<div class="col-md-12" style="padding-bottom:24px;">
<ul class="nav navtab nav-tabs" id="myTab" style="border-bottom:none;border-radius:1px;">
<li style="padding-right:13px;" class="active"><a style="" data-target="#higher_government_team" data-toggle="tab"><i class="fa fa-diamond" aria-hidden="true"></i> The Monarch/PM</a></li>
<li style="padding-right:13px;"><a style="" data-target="#senior_government_team" data-toggle="tab"><i class="fa fa-university"></i> Seniors</a></li>
<li style="padding-right:13px;"><a style="" data-target="#junior_government_team" data-toggle="tab"><i class="fa fa-university"></i> Juniors</a></li>
</ul>
</div>
<div class="col-md-8">
<div class="tab-content">
<div class="tab-pane active" id="higher_government_team">
<div class="panel panel-info">
<div class="panel panel-body">
higher gov here
</div>
</div>
</div>
<div class="tab-pane" id="senior_government_team">
<div class="panel panel-info">
<div class="panel panel-body">
senior gov here
</div>
</div>
</div>
<div class="tab-pane" id="junior_government_team">
<div class="panel panel-info">
<div class="panel panel-body">
#foreach ($juniorGovernment as $governmentMember)
{{ $governmentMember->user_id }}<br>
#endforeach
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
</div>
</div>
#include('frontend.footer')
Here is my controller for displaying the page:
<?php
namespace App\Http\Controllers\Frontend\User;
use Auth;
use Cache;
use Illuminate\Http\Request;
use App\Database\Website\User\Roleplay;
use App\Database\Website\Roleplay\GovernmentRole;
use App\Database\Website\Roleplay\Life\LifeEvents;
class GovernmentController
{
public function getView()
{
$higherGovernment = Cache::remember('government.higher_government', 1, function() {
return GovernmentRole::where('government_type', 'higher_government')->first()->stats;
});
$seniorGovernment = Cache::remember('government.senior_government', 1, function() {
return GovernmentRole::where('government_type', 'senior_ministers')->first()->stats;
});
$juniorGovernment = Cache::remember('government.junior_government', 1, function() {
return GovernmentRole::where('government_type', 'junior_ministers')->first()->stats;
});
return view('frontend.community.government', compact('juniorGovernment', 'seniorGovernment', 'higherGovernment', 'royalty'));
}
}
Now as you can see, I only select the first record where government_type matches. But the issue is I have multiple government roles with that government type and I want to get all the account stats for all records with that government type. I have looked at others suggestions and none of them work, either throwing an error or don't do what I want to do.
Now, I have modals for each Roleplay and GovernmentRoles, I have posted them both below.
GovernmentRole:
namespace App\Database\Website\Roleplay;
use Eloquent;
class GovernmentRole extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_government_roles';
public $timestamps = false;
protected $fillable = [];
public function stats(){
return $this->hasMany('App\Database\Website\User\Roleplay', 'government_id');
}
}
Roleplay:
use Eloquent;
class Roleplay extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_user_statistics';
public $timestamps = false;
protected $fillable = [];
public function user()
{
return $this->belongsTo('App\Database\Website\User\Player', 'user_id', 'id');
}
public function government_role()
{
return $this->belongsTo('App\Database\Website\Roleplay\GovernmentRole', 'government_id');
}
}
So what I am trying to achieve is not just grabbing all the Roleplay instances for the FIRST government role record in the database it finds but putting together ALL roleplay instances for ALL records that match government_type either higher_government, senior_ministers, or junior_ministers.
If I understand what you are asking, can you not do something like fetching the stats on your loop through in blade? For example (I removed the cache, its adding complexity to the question/answer without any benefit):
// controller
$higherGovernment = GovernmentRole::where('government_type', 'higher_government')->get();
// blade
#foreach($higherGovernment as $g)
{{ $g->id }}
{{ $g->name }}
#foreach($g->stats as $stat)
{{ $stat->id }}
{{ $stat->something }}
#endforeach
#endforeach

Loop Object Relationship Laravel

Here i'm trying to to loop through all my users with their related assignments. I have made the User->Assignment Relationship in the model. When I dd($students) I receive the array of students with their related assignments, however when I view this on the page I do not receive the loop of assignments. What could I have missed in the code? Im sure it's somewhere in the html I messed up.
User Model:
public function assignments()
{
return $this->hasMany('App\Assignment');
}
Assignment Model:
public function userAssignment()
{
return $this->belongsTo('App\User');
}
Controller:
$students = User::where('position','student')->with('assignments')->get();
Html:
#foreach($students as $student)
<div class="item{{{ $isFirst ? ' active' : '' }}}">
<div class = "deck">
<div class = "row marg">
<div class="col-md-8">
<div class = "stdnt">
<h1>Student Info</h1>
<h1>{{$student->name}}</h1>
<p>Program: {{$student->pack}}</p>
<p>Level: {{$student->level}}</p>
<p>Status: {{$student->status}}</p>
<p>Lesson: {{$student->lesson}}</p>
</div>
</div>
<div class = "col-md-4">
<div class = "teac">
<h1>Teacher Info</h1>
<h1>{{$student->teacher}}</h1>
<p>Picture</p>
<p>assign form</p>
<p>assign button</p>
</div>
</div>
</div>
</div>
<div class = "mask flow">
<div class = "row-fluid marg">
#foreach($student->assignments() as $assignment)
<div class = "ablock">
<h1>{{$assignment->title}}</h1>
<p>{{$assignment->created_at}}</p>
<p>{{$assignment->type}}</p>
<p>{{$assignment->body}}</p>
</div>
#endforeach
</div>
</div>
{{--*/ $isFirst = false; /*--}}
</div>
#endforeach
Don't call the assignments method. Simply access it as a property:
#foreach($student->assignments as $assignment)
// ^^
#endforeach

Categories