Pre-Populating Parent Child Form from DB - laravel

I have tried prepopulating the forms from DB records, not happening for child form, I have use all conventions for Laravel table, pivot table etc., still nothing. The array display with the dd('$allTariffs') but doesn't show on view file, please help am stuck with
ErrorException
foreach() argument must be of type array|object, null given
Edit Component Code
<?php
namespace App\Http\Livewire\Admin;
use App\Models\Products;
use App\Models\Tariffs;
use Livewire\Component;
class AdminEditTariffsComponent extends Component
{
// public $productId;
public $tariffId;
public $allTariffs = [];
public $rowProducts = [];
public $tariffName;
public function mount ($tariffId)
{
$this->rowProducts = Products::all();
$tariff = Tariffs::where('id', $tariffId)->first();
$this->tariffName = $tariff->tariff_name;
// $allTariffs = $tariff->products()->where('tariffs_id', $tariffId)->get()->toArray();
$allTariffs = $tariff->products->find($tariffId);
// var_dump($allTariffs) ;
// dd( $allTariffs);
foreach ($allTariffs->products as $product)
{
['productId' => $product->pivot->products_id, 'basicCharge' => $product->pivot->basic_charge, 'additionalCharge' => $product->pivot->additional_charge];
}
}
public function updateStatus()
{
$tariff = Tariffs::find($this->tariffId);
$tariff->tariff_name = $this->tariffName;
$tariff->created_by = auth()->user()->id;
$tariff->save();
foreach ($this->allTariffs as $product) {
$tariff->products()->sync($product['productId'],
['basic_charge' => $product['basicCharge'],
'additional_charge' => $product['additionalCharge']]);
}
session()->flash('message', 'Tariff added successfully!');
return redirect('/admin/tariffs/');
}
public function addProduct()
{
$this->allTariffs[] = ['productId' => '', 'basicCharge' => '', 'additionalCharge' => ''];
}
public function removeProduct($index)
{
unset($this->allTariffs[$index]);
$this->allTariffs = array_values($this->allTariffs);
}
public function render()
{
$rowProducts = Products::all();
return view('livewire.admin.admin-edit-tariffs-component',['rowProducts'=>$rowProducts])->layout('layouts.admin.base');
}
}
Edit View
<div class="container-fluid">
<!-- Begin Page Content -->
<!-- Page Heading -->
<div class="row">
<div class="col-lg-8">
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Edit Tariff</h6>
</div>
<div class="card-body">
<form wire:submit.prevent="editTariff">
#csrf
<div class="form-row">
<!-- Default input -->
<div class="form-group col-md-8">
<input type="text" class="form-control" placeholder="Enter Tariff Name"
wire:model="tariffName" required>
</div>
</div>
<hr>
<div class="card">
<div class="card-header">
<h6 class="text-primary">Products, Basic and Weight Charges</h6>
</div>
<div class="card-body">
<table class="table" id="products_table">
<thead>
<tr>
<th>Product</th>
<th>Basic Charge</th>
<th>Weight Charge</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach ($allTariffs as $index => $allTariff)
<tr wire:key="tariff-{{ $value->wireKey }}">
<td>
<select
wire:model="allTariffs.{{$index}}.productId"
class="custom-select custom-select-sm form-control form-control-sm">
<option value="">Select Product</option>
#foreach ($rowProducts as $product)
<option value="{{ $product->id }}">
{{ $product->product_name }}
</option>
#endforeach
</select>
</td>
<td>
<input type="text"
class="form-control custom-select-sm form-control form-control-sm"
placeholder="Basic Charge"
wire:model="allTariffs.{{$index}}.basicCharge" required>
</td>
<td>
<input type="text"
class="form-control custom-select-sm form-control form-control-sm"
placeholder="Weight Charge"
wire:model="allTariffs.{{$index}}.additionalCharge" required>
</td>
<td>
<a href="#" wire:click.prevent="removeProduct({{$index}})" class="btn btn-danger btn-circle btn-sm">
<i class="fas fa-trash"></i>
</a>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="row">
<div class="col-md-12">
<a href="#" wire:click.prevent="addProduct" class="btn btn-success btn-circle btn-sm">
<i class="fas fa-plus"></i>
</a>
</div>
</div>
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-3">
<button type="submit" class="form-control btn btn-small btn-primary">Edit
Tariff</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
Model File
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tariffs extends Model
{
use HasFactory;
protected $table = "tariffs";
public function products()
{
return $this->belongsToMany(Products::class, 'products_tariffs',
'products_id', 'tariffs_id')
->withPivot('basic_charge', 'additional_charge');
}
public function productstariffs()
{
return $this->hasMany(ProductsTariffs::class);
}
}
I have tried prepopulating the forms from DB records, not happening for child form, I have use all conventions for Laravel table, pivot table etc., still nothing. The array display with the dd('$allTariffs') but doesn't show on view file, please help am stuck with
ErrorException
foreach() argument must be of type array|object, null given .thankyou

In your foreach in your mount function, you are creating an array but you aren't assigning it to anywhere. Therefore, $allTariffs is empty.
Also, you're casting your variables by default as an array. You are setting $rowProducts as a Collection, however. But then in your render you are also getting the $rowProducts again. I'd suggest removing the = [] and removing the fetching of the $rowProducts each render.
public $allTariffs = [];
public $rowProducts;
public $tariffName;
public function mount ($tariffId)
{
$this->rowProducts = Products::all();
// This assumes the $tarrifId always exists. If this isn't the case, perhaps
// wrap the related code in an "if ($tariff instanceof Tariff)"
$tariff = Tariffs::find($tariffId);
$this->tariffName = $tariff->tariff_name;
foreach ($tariff->products as $product) {
$this->allTariffs[] = ['productId' => $product->id, 'basicCharge' => $product->pivot->basic_charge, 'additionalCharge' => $product->pivot->additional_charge];
}
}
public function render()
{
return view('livewire.admin.admin-edit-tariffs-component')->layout('layouts.admin.base');
}

Related

Why Does Image Read Null When I Try To Delete My Category?

I am trying to find a way to delete my category that I have created. I have the image stored in my public folder and I get the error attempt to read image is null, I think the error has to do with category_id being null. How can I retrieve it for my category object?
//Controller class
class Index extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $category_id;
//setting category_id
public function deleteCategory($category_id)
{
$this->category_id = $category_id;
}
public function destroyCategory() {
$category = Category::find($this->category_id);
// dd($this);
$path = 'uploads/category/'.$category->image;
if (File::exists($path)) {
File::delete($path);
}
$category->delete();
session()->flash('message', 'Category Deleted');
$this->dispatchBrowserEvent('close-modal');
}
public function render()
{
$categories = Category::orderBy('id', 'DESC')->paginate(10);
return view('livewire.admin.category.index', ['categories' => $categories]);
}
}
this is my component blades file that accompanies it.
//my blade file
<div>
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Category Delete</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form wire:submit.prevent="destroyCategory">
<div class="modal-body">
<h6>Are you sure you want to delete this data?</h6>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Yes. Delete</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
#if(session('message'))
<div class="alert alert-success">{{session('message')}}</div>
#endif
<div class="card-header">
<h4>
Category
Add Category
</h4>
</div>
<div class="card-body">
{{-- display all categories using livewire --}}
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($categories as $category)
<tr>
<td>{{$category->id}}</td>
<td>{{$category->name}}</td>
<td>{{$category->status == '1' ? "Hidden" : "Visible"}}</td>
<td>
Edit
<a href="#" wire:click="deleteCategory({{$category->id}})" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
Delete
</a>
</tr>
#endforeach
</tbody>
</table>
<div>
{{$categories->links()}}
</div>
</div>
</div>
</div>
</div>
#push('script')
<script>
window.addEventListener('close-modal', event => {
$('#deleteModal').modal('hide');
})
</script>
#endpush
I wanted to add my sugestion as a comment, however is to long and it doesn't look good when i add the code, so i need to add a post.
I see that you are using deleteCategory() to get category_id and set it on a public varaible public $category_id;, when you get the variable then you try to delete the category with destroyCategory().
If that is true you don't need to create 2 functions for that,
so instead try and use this:
public function deleteCategory($category_id) {
$category = Category::find($category_id);
$path = 'uploads/category/'.$category->image;
// dd($path); <- try this on the debbuger, to see the path
if (File::exists($path)) {
File::delete($path);
}
$category->delete();
session()->flash('message', 'Category Deleted');
$this->dispatchBrowserEvent('close-modal');
}
Just use the function deleteCategory with the code of destroyCategory, and let the paramenter $category_id, because deleteCategory gets the id from the view
wire:click="deleteCategory({{$category->id}})"

Laravel Livewire hide checked checkbox

in my laravel project in livewire component i need to hide/set display none or something a checked checkbox and later i need to show again if its needed . Any solutions? I could simply delete it but i wanna store it in DB
I tried do this:
https://larainfo.com/blogs/laravel-livewire-show-and-hide-div-example
but its hidding my all input checkboxes
here is my Livewire component code:
<?php
namespace App\Http\Livewire\Tasks\Types;
use App\Http\Livewire\Forms\BaseForm;
use App\Models\Task\Task;
use App\Models\Task\TaskStatus;
use App\Models\Task\TaskType;
use App\Models\Task\TaskTypeStatus;
use Livewire\Component;
use App\Traits\HasPosition;
use Mpdf\Tag\Input;
class TaskTypeStatusModal extends BaseForm
{
public $task_type_id = 0;
public $availableStatuses = [];
public $selectedStatuses = [];
public $selectedStatusesList = [];
public function mount($params = [])
{
$this->task_type_id = $params['task_type_id'];
$this->title = 'Edytuj statusy';
$this->availableStatuses = TaskStatus::orderBy('position')->get();
$this->selectedStatuses = TaskTypeStatus::where('task_type_id', $this->task_type_id)->pluck('task_status_id');
$this->selectedStatusesList = TaskTypeStatus::where('task_type_id', $this->task_type_id)->orderBy('position')->get();
}
public function submit()
{
foreach ($this->selectedStatuses as $status) {
TaskTypeStatus::create([
'task_type_id' => $this->task_type_id,
'task_status_id' => $status,
]);
}
$this->closeFromModal();
$this->emit( 'Zapisano');
$this->emit('list:refresh');
}
public function render()
{
return view('livewire.tasks.types.task-type-status-modal',[
$this->selectedStatusesList = TaskTypeStatus::where('task_type_id', $this->task_type_id)->orderBy('position')->get()
]);
}
public function reorder($list)
{
foreach ($list as $item) {
TaskTypeStatus::find($item['value'])->update(['position' => $item['order']]);
}
}
public function deleteStatus($id)
{
TaskTypeStatus::find($id)->delete();
}
and here is my blade code:
<div>
<form wire:submit.prevent="submit">
<div class="modal-header">
<h5 class="modal-title">{{ $title }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" wire:click.prevent="closeFromModal">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h6>Wybierz statusy</h6>
#forelse($availableStatuses as $availableStatus)
<div class="form-check checkbox">
<input class="form-check-input" name="status-{{ $availableStatus->id }}" id="status-{{ $availableStatus->id }}" wire:key="status-{{ $availableStatus->id }}"
wire:model.defer="selectedStatuses" type="checkbox" value="{{ $availableStatus->id }}"
wire:click="$toggle">
<label class="form-check-label" for="status-{{ $availableStatus->id }}">{{ $availableStatus->name }}</label>
</div>
#empty
<tr>
<td colspan="3">{{ __('Brak dostępnych statusów') }}</td>
</tr>
#endforelse
<hr>
<h6>Dodane statusy</h6>
<tr><span style="color:#3c4b64;font-size: 9pt"><b>{{ __('Przeciągnij za nazwę, aby zmienić kolejność.') }}</b></span></tr>
<ul class="list-group" wire:sortable="reorder">
#forelse ($selectedStatusesList as $selectedStatus)
<li class="list-group-item" value="{{ $selectedStatus->id }}" wire:sortable.item="{{ $selectedStatus->id }}" wire:key="selectedStatus-{{ $selectedStatus->id }}">
<td wire:sortable.handle>{{ __($selectedStatus->taskStatus->name) }}
<div class="float-right">
<button wire:click.prevent="deleteStatus({{ $selectedStatus->id }})" class="btn btn-sm btn-danger">{{ __('Usuń') }}</button>
</div>
</td>
</li>
#empty
<tr>
<td colspan="3">{{ __('Brak dodanych statusów') }}</td>
</tr>
#endforelse
</ul>
</div>
<div class="modal-footer">
<button wire:click.prevent="closeFromModal" class="btn btn-secondary" data-dismiss="modal">Anuluj</button>
<button type="submit" class="btn btn-primary">Zapisz</button>
</div>
</form>
</div>

Laravel Livewire uploads file only after second submit / button press

I want to create an almost simple file upload via Laravel/Livewire, but once submitting the form with two inputs and one file input, the form fields focus and standstill. However, after pressing the submit button again, it uploads as anticipated with a success message. How can this be achieved with the first button submit?
Livewire component
namespace App\Http\Livewire\Files;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\File;
class FilesForm extends Component
{
use WithFileUploads;
public $file;
public $name;
public $doctype;
public $doctypes;
public $doctypeparent;
public $docs;
public function mount($id)
{
$this->doctypeparent = $id;
}
public function save()
{
$validatedData = $this->validate([
'doctype' => 'required',
'file' => 'required|image|mimes:jpg,jpeg,png,svg,gif|max:10240',
]);
$filename = $this->file->store('files','public');
$validatedData['content_type_id'] = $this->doctype;
$validatedData['name'] = $this->name;
$validatedData['file'] = $filename;
$validatedData['user_id'] = Auth::id();
$validatedData['slug'] = uniqid();
File::create($validatedData);
session()->flash('message', 'Datei erfolgreich gespeichert.');
$this->doctype="";
$this->name="";
$this->file="";
$this->render();
//return redirect()->to('/fileupload');
}
public function render()
{
$this->doctypes = DB::table('content_type')
->select('content_type.id', 'content_type.strTitleDe')
->where('content_type.fkintContentGroup', '=', $this->doctypeparent)
->orderBy('content_type.intPriority')
->get();
$this->docs = File::all();
//dd($this->docs);
return view('livewire.files.files-form');
}
}
Livewire blade
<div class="file-form">
<form wire:submit.prevent="save">
#if (session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
<div class="form-group">
<label for="name">Typ</label>
<select class="form-control" id="doctype" name="doctype" wire:model="doctype">
<option value="">- - -</option>
#foreach ($doctypes as $doctype)
<option value="{{ $doctype->id }}">{{ $doctype->strTitleDe }}</option>
#endforeach
</select>
#error('doctype') <span class="error">{{ $message }}</span> #enderror
</div>
<div class="form-group">
<label for="name">Bezeichnung</label>
<input type="text" class="form-control" max="255" id="name" placeholder="" wire:model="name">
#error('name') <span class="text-danger">{{ $message }}</span> #enderror
</div>
<div class="form-group">
<div class="custom-file">
<label for="file">Datei:</label>
<input type="file" class="form-control" id="file" wire:model="file">
#error('name') <span class="error">{{ $message }}</span> #enderror
</div>
</div>
<button type="submit" class="btn btn-primary">Speichern</button>
</form>
<p></p>
<h3>Dokumente</h3>
<table>
<thead>
<tr>
<td>Typ</td>
<td>Title</td>
</tr>
</thead>
<tbody>
#foreach($docs as $doc)
<tr>
<td>Typ</td>
<td>{{ $doc->name}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
Not sure if this helps but.....While it looks like this could work, I never do actual form submits when using livewire - all of the data is bound with wire:model. There's no need to use a form at all. I just use buttons with wire:click and call whatever function saves the file.
Doing it that way I've had zero problems with file uploads.

adding data in table show me error when i add the relation ships

I am a beginner in laravel I made a relationship one to many between the table of father and the table of eleve after that when i try to add a a new student he shows this error
SQLSTATE[HY000]: General error: 1364 Field 'father_id' doesn't have a default value (SQL: insert into eleves (nom, prenom, adresse, date_naiss, sexe, nationnalite, niveau_scolaire, updated_at, created_at) values (mohamed, ferchichi, tunis, 2018-07-22, Un garçon, tunisen, 1, 2019-05-13 10:56:28, 2019-05-13 10:56:28))
how I can correct this problem i need your help
this is the table of eleve
public function up()
{
Schema::create('eleves', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('father_id');
$table->string('nom');
$table->string('prenom');
$table->date('date_naiss');
$table->string('sexe');
$table->string('nationnalite');
$table->string('niveau_scolaire');
$table->string('adresse');
$table->foreign('father_id')->references('id')->on('fathers')->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
}
the model of eleve
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Eleve extends Model
{
protected $fillable = ['nom', 'father_id', 'prenom', 'date_naiss', 'sexe', 'nationnalite', 'niveau_scolaire', 'adresse'];
public function father()
{
return $this->belongsTo('App\Father');
}
}
the model of father
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Father extends Model
{
protected $fillable = ['nom', 'prenom', 'adresse', 'num_tel', 'email', 'login', 'date_naissance ', 'password'];
public function user()
{
return $this->belongsTo(User::class);
}
public function eleve()
{
return $this->hasMany('App\Eleve');
}
and the blade of eleve
<section id="no-more-tables">
<table class="table table-bordered table-striped table-condensed cf">
<thead class="cf">
<tr>
<th>id-eleve</th>
<th>Nom</th>
<th>Prenom</th>
<th>Adresse</th>
<th>Age</th>
<th>Sexe</th>
<th>Nationnalité</th>
<th>Niveau scolaire </th>
<th>les actions</th>
</tr>
</thead>
<tbody>
#foreach($eleves as $eleve)
<tr>
<td class="numeric" data-title="id-parent">{{$eleve->id}}</td>
<td class="numeric" data-title="Nom">{{$eleve->nom}}</td>
<td class="numeric" data-title="Prenom">{{$eleve->prenom}}</td>
<td class="numeric" data-title="Adresse">{{$eleve->adresse}}</td>
<td class="numeric" data-title="Numéro telephone">{{$eleve->date_naiss}}</td>
<td class="numeric" data-title="Email">{{$eleve->sexe}}</td>
<td class="numeric" data-title="Login">{{$eleve->nationnalite}}</td>
<td class="numeric" data-title="Password">{{$eleve->niveau_scolaire}}</td>
<td>
<button href="#editEmployeeModal" class="btn btn-theme" data-target="#editEmployeeModal "
data-mytitle="{{$eleve->nom}}" data-myprenom="{{$eleve->prenom}}"
data-myadresse="{{$eleve->adresse}}" data-myage="{{$eleve->date_naiss}}"
data-mysexe="{{$eleve->sexe}}" data-mynationalite="{{$eleve->nationnalite}}"
data-myniveau="{{$eleve->niveau_scolaire}}" data-catid={{$eleve->id}} class="edit"
data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Edit"></i>
</button>
<button href="#deleteEmployeeModal" class="btn btn-theme" data-target="#deleteEmployeeModal"
data-catid={{$eleve->id}} class="delete" data-toggle="modal"> <i class="material-icons"
data-toggle="tooltip" title="Delete"></i> </button>
</td>
</tr>
</tbody>
#endforeach
</table>
<div class="text-center">
{{ $eleves->links() }}
</div>
<div class="clearfix">
<div class="hint-text">Affichage de <b>5</b> sur <b>25</b> entrées</div>
<div id="addEmployeeModal" href="create" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form action="{{route('eleves.store')}}" method="post">
{{csrf_field()}}
<div class="modal-header">
<h4 class="modal-title">Ajouter un éléve</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>nom</label>
<input type="text" id="nom" name="nom" class="form-control" required>
</div>
<div class="form-group">
<label>prenom</label>
<input type="text" id="prenom" name="prenom" class="form-control" required>
</div>
<div class="form-group">
<label>adresse</label>
<textarea name="adresse" id="adresse" class="form-control" required></textarea>
</div>
<div class="form-group">
<label for="start">Date Naissance</label>
<input type="date" id="date_naiss" name="date_naiss" value="2018-07-22" min="2018-01-01"
max="2030-12-31">
<!-- <label>Date Naissance</label>
<input type="text" name=" date_naiss" id="date_naiss" class="form-control" required>
</div> -->
</div>
<div class="form-group">
<div>
<input type="radio" id="sexe" name="sexe" value="une fille" checked>
<label for="sexe">une fille</label>
</div>
<div>
<input type="radio" id="sexe" name="sexe" value="Un garçon">
<label for="sexe">Un garçon</label>
</div>
</div>
<div class="form-group">
<label>Nationnalité</label>
<input type="text" name="nationnalite" id="nationnalite" class="form-control" required>
</div>
<div class="form-group">
<label>Niveau Scolaire</label>
<input type="text" name="niveau_scolaire" id="niveau_scolaire" class="form-control"
required>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Annuler">
<input type="submit" class="btn btn-success" value="Ajouter">
</div>
</form>
</div>
</div>
</div>
</div>
</section>
the controller of student
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Eleve;
class EleveController extends Controller
{
public function index()
{
$eleves = Eleve::paginate(5);
return view('admin.eleves',compact('eleves'));
}
public function store(Request $request)
{
Eleve::create($request->all());
session()->flash('success',' Cet nouvel éléve a été enregistré avec succés');
return redirect()->back();
}
public function update(Request $request, $id)
{
$eleve = Eleve::findOrFail($request->eleve_id);
$eleve->update($request->all());
session()->flash('success','Cet éléve a été modifié avec succés');
return redirect()->back();
}
public function destroy(Request $request)
{
$eleve = Eleve::findOrFail($request->eleve_id);
$eleve->delete();
session()->flash('success','Cet éleve a été supprimé avec succés');
return redirect()->back();
}
}
The father_id field in the eleves table is required. You either have to make it optional or, more likely, add it to your form.
To make the field optional replace this line
$table->unsignedBigInteger('father_id');
with
$table->unsignedBigInteger('father_id')->nullable();
To add it to the form you would probably use a <select>, something like:
<form ...>
<select name="father_id">
#foreach(\App\Father::all() as $father)
<option name="{{ $father->id }}">{{ $father->nom }}</option>
#endforeach
</select>
Note: It's bad practice to call the database inside a view file. A better approach would be to load the Fathers inside the controller and pass it to the view:
public function create()
{
$fathers = Father::all();
return view('...', ['fathers' => $fathers]);
}
and in the view:
<form ...>
<select name="father_id">
#foreach($fathers as $father)
<option name="{{ $father->id }}">{{ $father->nom }}</option>
#endforeach
</select>
in the EleveController i add use App\Father; and i add this function
public function create()
{
$fathers= Father::all();
return view('admin.eleves',compact('fathers'));
}
and in the eleve blade.php i add this
<select name="father_id">
#foreach($fathers as $father)
<option name="{{ $father->id }}">{{ $father->nom }}</option>
#endforeach
</select>
the problem is that shows me the same error "Undefined variable: fathers "

How to insert values to table 'users' in laravel 5.2?

I want to insert employee details username,area to the table 'users'.
I have the following codes of CreateEmployeeController and
createemployee.blade.php view file.
When I click on the menu Create Employee is will shows the following error
QueryException in Connection.php line 662:
SQLSTATE[42000]: Syntax error or access violation: 1066 Table/alias: 'users' non unique (SQL: select * from users inner join users on users.id = users.users_id where users.deleted_at is null)
Controller file :
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Controllers\AdminController;
use App\CreateEmployee;
use App\Employee;
use App\Users;
class CreateEmployeeController extends AdminController
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
public function addemployee()
{
$employee = CreateEmployee::all();
$employee =CreateEmployee::join('users','users.id','=','users.users_id')->get();
return view('app.admin.employee.employee',compact('employee','users'));
}
public function employeesave(Request $request)
{
$title = 'Add Employee';
$employee = new Employee();
$employee->name=$request->employee_name;
$employee ->area = $request->area;
$employee->save();
Session::flash('flash_notification', array('level' => 'success', 'message' => 'employee created successfully'));
return Redirect::action('Admin\CreateEmployeeController#addemployee');
}
public function updateemployee(Request $request)
{
Employee::where('id',$request->id)->update(array('name'=>$request->employee_name,'area'=>$request->area));
Session::flash('flash_notification', array('level' => 'success', 'message' => 'shop details updated successfully'));
return Redirect::action('Admin\CreateEmployeeController#addemployee',array('id' => $request->id));
}
public function editemployee($id)
{
$employee = Employee::where('id',$id)->get();
return view('app.admin.employee.editemployee',compact('employee'));
}
public function deleteemployee($id)
{
$employee = Employee::where('id',$id)->get();
return view('app.admin.employee.delete',compact('employee'));
}
public function deleteconfirms($id)
{
$employee = Employee::where('id',$id)->delete();
Session::flash('flash_notification', array('level' => 'success', 'message' => 'customer deleted successfully'));
return Redirect::action('Admin\CreateEmployeeController#addemployee');
}
public function destroy($id)
{
//
}
}
//view file
#extends('app.admin.layouts.default')
{{-- Web site Title --}}
#section('title') {{{ trans('site/user.register') }}} :: #parent #stop
#section ('styles')
#parent
<style type="text/css">
</style>
#stop
{{-- Content --}}
#section('main')
#include('utils.vendor.flash.message')
<div class="row">
<div class="page-header">
<h2>Add Employee</h2>
</div>
</div>
<div class="container-fluid">
<div class="row">
#include('utils.errors.list')
<form class="form-horizontal" role="form" method="POST" action="{{ URL::to('admin/addemployee') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label">Employee Name</label>
<div class="col-md-2">
<input type="text" class="form-control" name="employee_name"
required>
</div>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label" for="religion">Password</label>
<div class="col-md-2">
<input type="password" class="form-control" placeholder="Password" name="password" id="password" data-parsley-trigger="change" data-parsley-required="true" data-parsley-minlength="6" data-parsley-maxlength="14" required>
{!! $errors->first('cpassword', '<label class="control-label" for="cpassword">:message</label>')!!}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label" for="caste">Confirm Password</label>
<div class="col-md-2">
<input type="password" class="form-control" placeholder="Confirm Password" name="password_confirmation" id="password_confirmation" data-parsley-trigger="change" data-parsley-required="true" data-parsley-equalto="#password" data-parsley-minlength="6" data-parsley-maxlength="14" required>
{!! $errors->first('password_confirmation', '<label class="control-label" for="password_confirmation">:message</label>')!!}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label">Area</label>
<div class="col-md-2">
<input type="text" class="form-control" name="area"
required placeholder="Area">
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-2 col-md-offset-2">
<button type="submit" class="btn btn-primary">
Add
</button>
</div>
</div>
</form>
</div>
</div>
<div class="invoice-content">
<div class="table-responsive">
<div class="col-md-offset-2">
<table class="table table-invoice">
<thead>
<tr>
<th>Employee Name</th>
<th>Area</th>
</tr>
</thead>
</div>
</div>
<tbody>
#foreach($addemployee as $employee)
<tr>
<td>{{$employee->employee_name}}</td>
<td>{{$employee->area}}</td>
<td>
Edit
<a onclick="return confirm('Are you Sure you want to do this Action!'); style.backgroundColor='#84DFC1'; " href="employee/delete/{{$employee->id}}">delete</a>
</td>
</tr>
#endforeach
#if(!count($employee))
<tr><td>NO data found </td></tr>
#endif
</tbody>
</tbody>
</table>
{{--</div>--}}
{{--</div>--}}
{{--</div>--}}
</div>
</div>
#endsection
I can't get the full idea about your problem, but as upto me I understand that - You are using same table/column names in your join statement, you can do this as:
$employee = CreateEmployee::join('users', 'create_employees.id','=', 'users.employee_id')->get();
Hope this helps!

Resources