How update values Many To Many Laravel - php

How do I update an edit field in laravel?
I've tried the sync () method, detach with atach ()
unsuccessfully, I ask your help with this.
I really appreciate anyone who can help me with this
Remembering, I already managed to save the values ​​with the create method, follow the codes:
My controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Pedido;
use App\Models\Cliente;
use App\Models\Produto;
class PedidosController extends Controller
{
/**
* mostrar conteudo no index
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$pedidos = Pedido::orderBy('id', 'asc')->paginate(2000);
return view('pedidos.index', compact('pedidos'));
}
/**
* Mostra o form para criar um novo pedido.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$clientes = Cliente::all();
$produtos = Produto::all();
return view('pedidos.create', compact('clientes', 'produtos'));
}
/**
* armazena um novo pedido pra enviar ao BD
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'status' => 'required',
'clientes_id' => 'required',
'produtos_id' => 'required'
]);
$pedido = Pedido::create($request->only([
'pedidos_id',
'produtos_id',
'clientes_id'
]));
$cliente = Cliente::find($request->clientes_id);
$pedido->clientes()->save($cliente);
$produto = Produto::find($request->produtos_id);
$pedido->produtos()->attach($produto);
return redirect()->route('pedidos.index')
->with('success', 'Pedido cadastrado com sucesso');
}
/**
* Exibe um pedido
*
* #param \App\Models\Pedido $pedido
* #return \Illuminate\Http\Response
*/
public function show(Pedido $pedido)
{
return view('pedidos.show', compact('pedido'));
}
/**
* Exibe um pedido para edição
*
* #param \App\Models\Pedido $pedido
* #return \Illuminate\Http\Response
*/
public function edit(Pedido $pedido)
{
$clientes = Cliente::all();
$produtos = Produto::all();
return view('pedidos.edit', compact('pedido', 'clientes', 'produtos'));
}
/**
* Atualiza um pedido no BD
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Pedido $pedido
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Pedido $pedido)
{
$request->validate([
'status' => 'required',
'clientes_id' => 'required',
'produtos_id' => 'required',
]);
$pedido->update($request->all());
return redirect()->route('pedidos.index')
->with('success', 'Pedido atualizado com sucesso');
}
/**
* Remove um pedido do BD
*
* #param \App\Models\Pedido $pedido
* #return \Illuminate\Http\Response
*/
public function destroy(Pedido $pedido)
{
$pedido->delete();
return redirect()->route('pedidos.index')
->with('success', 'Pedido deletado com sucesso');
}
}
my edit:
#extends('layouts.app')
#section('content')
<div class="container content">
<div class="row">
<div class="col-md">
<p class="text-center fs-1">Editar o pedido nº{{$pedido->id}}</b></p>
<div class="float-left">
<a class="btn btn-primary" href="{{ route('pedidos.index') }}" title="Voltar"> <i class="fas fa-backward "></i> </a>
</div>
</br>
#if ($errors->any())
<div class="alert alert-danger">
<strong>Ops!</strong> Há um problema com seu Pedido<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="row h-100">
<div class="col">
<form action="{{ route('pedidos.update', $pedido->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<label for="selectBox"> Cliente selecionado: </label>
<select style=width:400px name="clientes_id" class="form-control" onfocus="this.selectedIndex = -1;">
#foreach ($pedido->clientes as $cliente)
<option selected value="{{ $cliente->id}}">{{ $cliente->nome}}</option>
#endforeach
#foreach($clientes as $cliente)
<option value="{{ $cliente->id}}">{{ $cliente->nome}}</option>
#endforeach
</select>
</br>
<div class="custom-select">
<label for="selectBox"> Status selecionado: </label>
<select style=width:400px name="status" class="form-control" onfocus="this.selectedIndex = -1;">
<option selected> {{ $pedido->status }}</option>
<option value=aberto>Em aberto</option>
<option value=pago>Pago</option>
<option value=cancelado>Cancelado</option>
</select>
</div>
</br>
<label for="selectBox"> Escolha um produto: </label>
<select style=width:400px class="form-control" name="produtos" id="selectBox" onfocus="this.selectedIndex = -1;" onchange="addProduct(options);">
#foreach ($produtos as $produto)
<option value="{{ $produto->id}}">{{ $produto->nome}}</option>
#endforeach
</select>
</br></br>
<table class="table">
<thead>
<tr>
<th>Código Produto</th>
<th>Produto selecionado</th>
<th>Remover</th>
</tr>
</thead>
<tbody id="tbody">
#foreach ($produtos as $key => $produto)
<tr>
<td>
<input type="hidden" name="produtos_id[{{$key}}]" value="{{ $produto->id}}">{{ $produto->id}}
</td>
<td>
{{ $produto->nome}}
</td>
<td>
<input type='button' value='Remover' onclick='removeProduct()' />
</td>
</tr>
#endforeach
</tbody>
</table>
</br>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Enviar</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
var table = document.getElementById('tbody');
var count = linhas;
function addProduct(product) {
table.innerHTML += "<tr><td><input type='hidden' name='produtos_id[" + count + "]' value='" + product[product.selectedIndex].value + "'>" + product[product.selectedIndex].value + "</td><td>" + product[product.selectedIndex].innerText + "</td><td><input type='button' value='Remover' onclick='removeProduct()'/></tr></td>";
count++;
}
function removeProduct() {
var td = event.target.parentNode;
var tr = td.parentNode;
tr.parentNode.removeChild(tr);
count--;
}
</script>
#endsection
Pedido model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Pedido extends Model
{
protected $table = 'pedidos';
public $timestamps = true;
protected $fillable = [
'status',
'clientes_id',
'created_at'
];
public function clientes()
{
return $this->hasMany(Cliente::class, 'id', 'clientes_id');
}
public function produtos()
{
return $this->belongsToMany(Produto::class, 'pedidos_produtos', 'pedidos_id', 'produtos_id');
}
}
Produto Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Produto extends Model
{
use HasFactory;
protected $table = 'produtos';
public $timestamps = true;
protected $casts = [
'preco' => 'float'
];
protected $fillable = [
'nome',
'descricao',
'preco',
'quantidade',
'created_at'
];
public function pedidos()
{
return $this->belongsToMany(Pedido::class, 'pedidos_produtos', 'produto_id', 'pedidos_id');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Produto extends Model
{
use HasFactory;
protected $table = 'produtos';
public $timestamps = true;
protected $casts = [
'preco' => 'float'
];
protected $fillable = [
'nome',
'descricao',
'preco',
'quantidade',
'created_at'
];
public function pedidos()
{
return $this->belongsToMany(Pedido::class, 'pedidos_produtos', 'produto_id', 'pedidos_id');
}
}

you need to try this code. it will work.
$produtoId = [];
foreach ($produto as $pdt) {
$produtoId[] = $pdt->id;
}
$pedido->produtos()->sync($produtoId);
$pedido->update($request->all());

Related

laravel livewire - Invalid column name 'id' on update of a wire:modal

I get a the below error when I try to update the modal text after a search performed
select * from [test] where [test].[id] in (?)
\vendor\laravel\framework\src\Illuminate\Database\Connection.php:703
I have added a primary key name in the model that is different. See the model class:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Test extends Model
{
use HasFactory;
/**
* The primary key associated with the table.
*
* #var string
*/
protected $primaryKey = 'testId';
/**
* Indicates if the model's ID is auto-incrementing.
*
* #var bool
*/
public $incrementing = false;
/**
* The data type of the auto-incrementing ID.
*
* #var string
*/
protected $keyType = 'string';
protected $connection = 'sqlsrv2';
protected $table = "test";
}
Here is the livewire class:
<?php
namespace App\Http\Livewire;
use App\Models\TestSubItems;
use App\Models\Test;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
class TestApp extends Component
{
use AuthorizesRequests;
public $search = '';
public $items = null;
public $subItems = null;
public $message = '';
public $warning = false;
public function render()
{
return view('livewire.bin-app');
}
public function search()
{
$this->items = null;
$this->subItems = null;
if ($this->search) {
$this->items = Test::where('ItemNo', $this->search)->get();
if (!$this->items->isEmpty()) {
$this->warning = false;
$this->message = '';
$this->subItems = TestSubItems::where('ItemNo', $this->search)->get();
}
if ($this->items->isEmpty()) {
$this->message = 'Not found';
}
}
}
}
Blade file:
<div>
<div class="grid grid-cols-1 gap-4 p-4">
<div>
<label for="search" class="text-right">Item Code: </label>
<input wire:model="search" autofocus="autofocus"
class="block appearance-none w-full bg-gray-200 border border-gray-200 text-gray-700 py-3 px-4 pr-8 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500"
id=" search"
/>
</div>
#if ($message != '')
<div class="mb-5 mt-5 bg-red-50 rounded-md py-4 px-4">
<p class="font-bold text-green-500">
{{ $message }}
</p>
</div>
#endif
<div>
<button wire:click="search()" class="btn btn-primary">Search</button>
</div>
</div>
#if (isset($items))
#if (!$items->isEmpty())
<div class="grid grid-cols-1 gap-4 p-4">
#foreach($items as $item)
<h2 class="md:text-3xl text-xs"><span class="font-bold">Code:</span>
{{ $item->code }}
</h2>
#endforeach
</div>
#endif
#endif
#if (isset($subItems))
#if (!$subItems->isEmpty())
<table class="table w-full">
<thead>
<th class="border-2 border-gray-50">
Item No
</th>
<th class="border-2 border-gray-50">
Type
</th>
</thead>
<tbody>
#foreach($subItems as $item)
<tr>
<td class="border-2 border-gray-50">
{{ $item->itemNo }}
</td>
<td class="border-2 border-gray-50">
{{ $item->type }}
</td>
</tr>
#endforeach
</table>
#endif
#endif
</div>
This only happens after the initial search. I think it is related to the Model some way but not sure how.
Any help would be great to solve this.
I run your code, I only added to the TestSubItems the next properties
class TestSubItems extends Model
{
use HasFactory;
/**
* The primary key associated with the table.
*
* #var string
*/
protected $primaryKey = 'itemNo';
/**
* Indicates if the model's ID is auto-incrementing.
*
* #var bool
*/
public $incrementing = false;
/**
* The data type of the auto-incrementing ID.
*
* #var string
*/
protected $keyType = 'string';
}

Laravel select models based on relationship

I am working on a library application and I want to create a function where the user can rent out a book to a customer. However, I want the books that are rented out right now to not show up in the select box when renting out another book.
I have looked up several articles about this, but couldn't really make up a solution so I would be happy about any help.
The idea is, that when a book has the attribute "maxreturndate" set it won't show up.
CheckedOutController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\CheckedOut;
use App\Book;
use App\Reader;
class CheckedOutController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$checkedOuts = CheckedOut::with(['book', 'reader'])->get();
return view('checkedouts/index', compact('checkedOuts'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$books = Book::all();
$readers = Reader::all();
return view('checkedouts/create', compact('books','readers'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'book_id' => 'required',
'reader_id' => 'required',
'maxreturndate' => 'required|date',
'returndate' => 'nullable',
]);
$checkedOut = CheckedOut::create($validatedData);
return redirect('checkedouts')->with('success', 'Buch wurde erfolgreich verliehen!');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
index.blade.php
#extends('layout')
#section('title')
<title>Alle ausgeliehen Bücher</title>
#section('content')
<style>
.uper {
margin-top: 40px;
}
</style>
<div class="uper">
#if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div><br />
#endif
<table class="table table-hover">
<thead>
<tr>
<td>ID</td>
<td>Titel</td>
<td>Verliehen an</td>
<td>Verleihdatum</td>
<td>Fällig am</td>
<td>Zurückgebracht am</td>
<td colspan="2">Funktionen</td>
</tr>
</thead>
<tbody>
#foreach($checkedOuts as $checkedOut)
<tr>
<td>{{$checkedOut->id}}</td>
<td>{{$checkedOut->book->title}}</td>
<td>{{$checkedOut->reader->name}}</td>
<td>{{$checkedOut->created_at}}</td>
<td >{{$checkedOut->maxreturndate}}</td>
<td>{{$checkedOut->returndate}}</td>
<td></td>
<td>Bearbeiten</td>
<td>Anzeigen</td>
<td>
<form action="{{ route('checkedouts.destroy', $checkedOut->id)}}" method="post">
#csrf
#method('DELETE')
<button class="btn btn-danger" type="submit">Löschen</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
<div>
#endsection
Migrations:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCheckedOutsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('checked_outs', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('book_id')->unsigned();
$table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
$table->bigInteger('reader_id')->unsigned();
$table->foreign('reader_id')->references('id')->on('readers')->onDelete('cascade');
$table->date('maxreturndate');
$table->date('returndate')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('checked_outs');
}
}
create.blade.php
#extends('layout')
#section('title')
<title>Buch verleihen</title>
#section('stylesheets')
<script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet" />
#endsection
#section('content')
<style>
.uper {
margin-top: 40px;
}
</style>
<div class="card uper">
<div class="card-header">
Buch verleihen
</div>
<div class="card-body">
<form method="post" action="{{ route('checkedouts.store') }}">
<div class="form-group">
#csrf
<label for="book_id">Buch:</label>
<select name="book_id" class="form-control select2-single <!-- #error('book_id') is-invalid #enderror -->">
#foreach ($books as $book)
<option value="{{ $book->id }}">{{ $book->title }}</option>
#endforeach
</select>
#error('book_id')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
</div>
<div class="form-group">
<label for="reader_id">Verleihen an:</label>
<select name="reader_id" class="form-control select2-single <!-- #error('reader_id') is-invalid #enderror -->">
#foreach ($readers as $reader)
<option value="{{ $reader->id }}">{{ $reader->name }}</option>
#endforeach
</select>
#error('reader_id')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
</div>
<div class="form-group">
<label for="maxreturndate">Zurückbringen bis:</label>
<input type="date" class="form-control" name="maxreturndate" />
#error('name')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
</div>
<button type="submit" class="btn btn-primary">Verleihen</button>
</form>
</div>
</div>
<script type="text/javascript">
$(".select2-single").select2();
</script>
#endsection
The relationship between the 3 Models:
Book:
public function checkedOut(){
return $this->hasOne(CheckedOut::class);
}
Reader:
public function checkedOut()
{
return $this->belongsTo(CheckedOut::class);
}
CheckedOut:
public function book(){
return $this->belongsTo(Book::class);
}
public function reader(){
return $this->belongsTo(Reader::class);
}
My suggestion is to set up Books and Readers with a many-to-many relationship. Now, your models could look like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
class Book extends Model
{
public function readers()
{
return $this
->belongsToMany(\App\Reader::class, 'checked_outs')
->using(\App\Checkout::class)
->withPivot(['returndate', 'maxreturndate']);
}
}
class Reader extends Model
{
public function books()
{
return $this
->belongsToMany(\App\Book::class, 'checked_outs')
->using(\App\Checkout::class)
->withPivot(['returndate', 'maxreturndate']);
}
}
class Checkout extends Pivot
{
// this should be named `book_reader` but we override it here
$table = "checked_outs";
$dates = [
"maxreturndate",
"returndate",
];
}
I have created a pivot model which isn't necessary, but allows you to operate directly on the pivot table and cast the extra attributes to dates automatically. Whether this is useful is a matter of opinion. You should rename the checked_outs table to book_reader which is the naming convention that Laravel expects for a pivot table.
Getting the books that aren't checked out is simple enough to do as follows, using the doesntHave method to check for absence of a relationship.
public function create()
{
$books = Book::doesntHave("readers")->get();
$readers = Reader::all();
return view('checkedouts/create', compact('books','readers'));
}
And "checking out" a book could look like this:
public function store(Request $request)
{
$reader = Reader::find($request->reader_id);
$reader
->books()
->attach(
$request->book_id,
["returndate" => Carbon\Carbon::now()->addDays(7)]
);
}
when a book has the attribute "maxreturndate" set it won't show up
Since you did not specify in your migration, I am going to assume here that you have a maxreturndate nullable field in your books table, then you should be able to simply create a local scope when you want your list of "not rented" books.
Here's an example on creating a notRented scope:
// in your Book model define the local scope
public function scopeNotRented($query){
return $query->whereNotNull('maxreturndate');
}
// in the create method of your controller
public function create()
{
$books = Book::notRented()->get();
$readers = Reader::all();
return view('checkedouts/create', compact('books','readers'));
}

Why do I get this error : Undefined variable: product (View: C:\xampp\htdocs\basic\resources\views\mycart.blade.php)?

I'm new to Laravel in here and upon building a project I'm having errors:
Undefined variable: product (View: C:\xampp\htdocs\basic\resources\views\mycart.blade.php)
after checking up on the errors to fix still persists and I hope you guys can help me out. Thanks in advance
mycart blade code:
#extends('layouts.app')
#section('content')
#if(Session::has('cart'))
<div class="container">
<b class="text-uppercase" style="color: darkgrey; font-size: 18px;">Item(s)</b>
<div class="row">
#foreach($products as $products)
<div class="col-sm-12 col-lg-2" style="padding-bottom: 12%;">
<div class="cart-item-container">
<a href="ads/{{strtolower(str_replace(" ","-",$product->name))}}"><div class="item-image"><img src="{{asset($product->image)}}" class="item-image">
</div>
<div class="item-tag" >
<p class="h5 text-capitalize">{{$product->name}}</p></a>
<p class="h4">GH¢ {{$product->price}}</p>
<div class="form-group" style="float: left; width: 25%;">
<select class="form-control" id="exampleFormControlSelect1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
</div>
<div style="float: right;"><ul class="list-inline">
<li><p class="text-primary text-capitalize"><span class="glyphicon glyphicon-heart-empty"></span></span></li>
<li><p class="text-muted text-capitalize"><span class="glyphicon glyphicon-trash"></span></p></li>
</ul>
</div>
</div>
</div>
</div>
#endforeach
</div>
<div style="float: right;"><ul class="list-inline">
<li><p class="text-primary text-capitalize"><span class="glyphicon glyphicon-heart-empty"></span></span></li>
<li><p class="text-muted text-capitalize"><span class="glyphicon glyphicon-trash"></span></p></li>
</ul>
</div>
</div>
</div>
</div>
</div>
#else
#endif
<div style="float: right; clear: both;">
<table class="table">
<tr>
<th scope="row">Total</th>
<td>GH¢ {{ $totalPrice }}</td>
</tr>
</table>
<ul class="list-inline">
<li><button class="btn btn-plain text-uppercase">contine shopping</button></li>
<li><button class="btn btn-primary text-uppercase">proceed to checkout</button></li>
</ul>
</div>
</div>
</div>
<hr style="border: 1px solid rgb(215,215,215); width: 85%;">
<div class="container" style="margin-top: 5%;">
<b class="text-uppercase" style="color: darkgrey; font-size: 18px;">saved item(s)</b>
<div class="row">
</div>
</div>
#endsection
And ProductController controller Code:
<?php
namespace App\Http\Controllers;
use App\Item;
use Illuminate\Http\Request;
use App\Cart;
use App\Http\Requests;
use Session;
class ProductController extends Controller
{
public function addToCart(Request $request, $id)
{
$product = Item::find($id);
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($product, $product->id);
$request->session()->put('cart', $cart);
return redirect()->route('welcome.index');
}
public function getCart()
{
if (!Session::has('cart')) {
return view('mycart');
}
$oldCart = Session::get('cart');
$cart = new Cart($oldCart);
return view('mycart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice]);
}
}
In your getCart() method you are returning the products if there is a Session variable for cart. However, if there is no Session cart variable, you are returning the view without any variable attached here:
if (!Session::has('cart')) {
return view('mycart');
}
To fix the missing variable error in your blade view, define an empty value to $products and return it along with the view from your controller:
if (!Session::has('cart')) {
$products = [];
$totalPrice = 0;
return view('mycart', compact('products', 'totalPrice));
}
Note - you will have the same problem with $totalPrice so I have defined 0 for that variable to prevent the error.
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::latest()->paginate(5);
return view('products.index',compact('products'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('products.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'detail' => 'required',
]);
Product::create($request->all());
return redirect()->route('products.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function show(Product $product)
{
return view('products.show',compact('products'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function edit(Product $product)
{
return view('products.edit',compact('product'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Product $product)
{
$request->validate([
'name' => 'required',
'detail' => 'required',
]);
$product->update($request->all());
return redirect()->route('products.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$product->delete();
return redirect()->route('products.index')
->with('success','Product deleted successfully');
}

Get the name of authenticated user and store it

I have a form in which you submit a "project". One of the field is "created by", but the user does not update this, it gets the name of the authenticated user in that moment and inserts it into the db.
I know how to retrieve the user's name, but the problem is that when I login with another user, then all the name change, because I store the name each time.
This is my project controller
<?php
namespace App\Http\Controllers;
use App\Project;
use App\Client;
use Auth;
use Illuminate\Http\Request;
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('projects.index', [
'project' => Project::all()
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
if (Auth::user()->role != 1){
return redirect()->back();
}else{
return view('projects.create',[
'project' => new Project,
'client' => new Client
]);
}
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $r)
{
$validatedData = $r->validate([
'proj_title' => 'required|max:100',
'client_id' => 'required',
'proj_desc' => 'required',
]);
$currentUser = Auth::user()->name;
$r['created_by'] = $currentUser;
$project = Project::create($r->all());
return redirect('/projects')->with('store','');
}
/**
* Display the specified resource.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function show(Project $project)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
return view('projects.edit', compact('project'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function update(Request $r, Project $project)
{
$project->update($r->all());
return redirect('/projects')->with('update','');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
$project->delete();
return redirect('/projects')->with('delete','');
}
}
And this is my index
#section('content')
<div class="row">
<div class="col">
#if (Auth::user()->role == 1)
<a class="btn btn-success" href="/projects/create">Add Project</a>
#endif
</div>
<div class="col"></div>
<div class="col">
#if(session()->has('store'))
<div class="alert alert-success mt-2" role="alert">
<strong>Project created</strong>
</div>
#elseif(session()->has('update'))
<div class="alert alert-success mt-2" role="alert">
<strong>Project updated</strong>
</div>
#elseif(session()->has('delete'))
<div class="alert alert-success mt-2" role="alert">
<strong>Project deleted</strong>
</div>
#endif
</div>
</div>
<br>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Project Id</th>
<th>Title</th>
<th>Description</th>
<th>Client Id</th>
<th>Created by</th>
<th>Created on</th>
#if (Auth::user()->role==1)
<th>Admin</th>
#endif
</tr>
</thead>
<tbody class="">
#foreach ($project as $project)
<tr>
<td>{{$project->proj_id}}</td>
<td>{{$project->proj_title}}</td>
<td>{{$project->proj_desc}}</td>
<td>{{$project->client_id}}</td>
<td>{{$project->Auth::user()->name}}</td>
<td>{{$project->created_at}}</td>
#if (Auth::user()->role==1)
<td>
<div class="dropdown">
<button class="btn btn-danger dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Action</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="{{route('projects.edit',$project)}}">Edit</a>
<form method="POST" action="{{route('projects.destroy',$project)}}" onsubmit="return confirm('Are you sure you want to delete this?')">
#method('DELETE')
#csrf
<button class="dropdown-item" type="submit">Delete</button>
</form>
</div>
</div>
</td>
#endif
</tr>
#endforeach
</tbody>
</table>
#endsection
I think your problem is that you are using:
{{ $project->Auth::user()->name }}
instead of
{{ $project->created_by }}

Laravel display name from database

I have a new problem. I'll try to give enough information.
I'm trying to display the names of the employees that have visited the customers, but as you can see it displays the names of the customers. Instead of Bryan or Granucci (these are the customers), it should say Madmin (I have only one user at the moment).
Screenshot
This is the drafts page
I'll add the code form my view, controller and model.
Drafts View
#extends('app')
#section('content')
#include('nav')
<div class="container">
#include('flash')
<div class="row">
<div class="col-md-2">
{!! Form::open(['method' => 'GET', 'action' => 'DraftsController#create']) !!}
{!! Form::submit('Create new draft', ['class' => 'btn btn-primary form-control']) !!}
{!! Form::close() !!}
</div>
</div>
<hr>
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">Search drafts</div>
<div class="panel-body">
{!! Form::open(array('url' => 'drafts/search', 'method' => 'post')) !!}
<div class="form-group">
<div class="col-md-2" align="right">
{!! Form::label('customer_name', 'Customer:') !!}
</div>
<div class="col-md-6">
{!! Form::text('customer_name', null, ['class' => 'form-control typeahead tt-query', 'autocomplete' => 'off', 'spellcheck' => 'false', 'placeholder' => 'Search...']) !!}
</div>
<div class="col-md-2" align="right">
{!! Form::label('customer_id', 'Customer ID:') !!}
</div>
<div class="col-md-2">
{!! Form::text('customer_id', null, ['class' => 'form-control', 'readonly' => 'readonly']) !!}
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-md-2" align="right">
{!! Form::label('descr', 'Article:') !!}
</div>
<div class="col-md-6">
{!! Form::text('descr', null, ['class' => 'form-control typeahead tt-query', 'autocomplete' => 'off', 'spellcheck' => 'false', 'placeholder' => 'Search...']) !!}
{!! Form::hidden('reportgroup', null, ['class' => 'form-control']) !!}
</div>
<div class="col-md-2" align="right">
{!! Form::label('article_id', 'Article ID:') !!}
</div>
<div class="col-md-2">
{!! Form::text('article_id', null, ['class' => 'form-control', 'readonly' => 'readonly']) !!}
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-md-2" align="right">
{!! Form::label('reference', 'Reference:') !!}
</div>
<div class="col-md-10">
{!! Form::text('reference', null, ['class' => 'form-control']) !!}
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-md-12" align="right">
{!! Form::submit('Search', ['class' => 'btn btn-primary form-control']) !!}
</div>
</div>
{!! Form::close() !!}
#include('errors')
</div>
</div>
<div class="panel panel-default">
{!! Form::open(['method' => 'POST', 'action' => 'DraftsController#invoice']) !!}
<div class="panel-heading">Search results</div>
<div class="panel-body">
<table class="table">
<tr>
<th> </th>
<th>No</th>
<th>Employee</th>
<th>Customer</th>
<th>Reference</th>
<th>Draft created</th>
<th>Work date</th>
<th style="text-align:right">Total excl. VAT</th>
<th> </th>
</tr>
<?php $count = 0; ?>
#foreach ($result as $draft)
<tr>
<td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
<td>{{ $draft['id'] }}</td>
<td>{{$draft['name'] }} ({{ $draft['user_id'] }})</td>
<td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
<td>{{ $draft['reference'] }}</td>
<td>{{ $draft['created_at'] }}</td>
<td></td>
<td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
<td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
</tr>
<?php $count++ ?>
#endforeach
</table>
<?php
if ($count == 0) {
print "No results";
}
else {
?>
<table>
<tr>
<td>
{!! Form::submit('Create invoice for selected drafts', ['class' => 'btn btn-primary form-control']) !!}
</td>
<td>
with invoice date
</td>
<td>
<input class="form-control" name="createDate" type="date" id="createDate" value="{{date('Y-m-d')}}">
</td>
<td>
and mail them to customer
</td>
<td>
<input type="checkbox" id="mailThem" name="mailThem">
</td>
</tr>
</table>
{!! Form::close() !!}
<?php
}
?>
</div>
</div>
</div>
</div>
</div>
#include('jsonArticles')
#include('jsonCustomers')
<script src="{{ asset('/js/typeahead.js') }}"></script>
<script src="{{ asset('/js/customers.js') }}"></script>
<script src="{{ asset('/js/articles.js') }}"></script>
#stop
Draftsheader Model
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class DraftHeader extends Model {
public function customer()
{
return $this->belongsTo('App\Customer');
}
public function user()
{
return $this->belongsTo('App\User');
}
public function lines()
{
return $this->hasMany('App\DraftLine');
}
protected $fillable = [
'user_id',
'employee_name',
'customer_id',
'name',
'name2',
'address',
'postcode',
'town',
'country',
'reference'
];
}
Drafts Controller
<?php
namespace App\Http\Controllers;
use Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Article;
use App\Customer;
use App\User;
use App\DraftHeader;
use App\DraftLine;
use App\InvoiceHeader;
use App\InvoiceLine;
use App\InvoiceMail;
use App\Http\Requests\DraftRequest;
use App\Http\Requests\DraftSearchRequest;
use App\Http\Requests\DraftLinesRequest;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
class DraftsController extends Controller {
/*
|--------------------------------------------------------------------------
| ArticlesController
|--------------------------------------------------------------------------
|
| Controller for Metis draft tasks
|
*/
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('auth:admin');
}
/**
* Get all articles
*
* #return array()
*/
private function allArticles() {
$allArticles = array();
$ff = Article::All()->toArray();
foreach ($ff as $ff1) {
$allArticles[] = array('name' => $ff1['descr'], 'id' => $ff1['id']);
}
return $allArticles;
}
/**
* Get all customers
*
* #return array()
*/
private function allCustomers() {
$allCustomers = array();
$ff = Customer::All()->toArray();
foreach ($ff as $ff1) {
$allCustomers[] = array('name' => $ff1['name'], 'id' => $ff1['id']);
}
return $allCustomers;
}
/**
* Get all uers
*
* #return array()
*/
private function allUsers() {
$allUsers = array();
$ff = User::All()->toArray();
foreach ($ff as $ff1) {
$allUsers[] = array('name' => $ff1['name'], 'id' => $ff1['id']);
//dd($allUsers);
}
return $allUsers;
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index() {
// Use request saved in session if applicable
$result = array();
if (Session::has('draft_search_request')) {
$request = Session::get('draft_search_request');
//dd($request);
$result = DraftHeader::query();
if (strlen(trim($request['customer'])) > 0) {
$result->where('name', 'LIKE', "%" . $request['customer'] . "%");
}
if (strlen(trim($request['user'])) > 0) {
$result->where('name', 'LIKE', "%" . $request['user'] . "%");
}
if (strlen(trim($request['reference'])) > 0) {
$result->where('reference', 'LIKE', "%" . $request['reference'] . "%");
}
if (strlen(trim($request['article'])) > 0) {
$result->DraftLine()->where('descr', 'LIKE', "%" . $request['article'] . "%");
}
//dd($result->toSql());
$result = $result->get()->toArray();
//dd($result);
}
else {
$result = DraftHeader::query()->where('created_at', '>', Carbon::yesterday())->get()->toArray();
}
// Get the total amount for each draft draft
$totals = array();
foreach ($result as $value) {
$total = DraftLine::selectRaw('sum(qty*netamount) AS total')->where('draft_header_id', '=', $value['id'])->get()->toArray();
$totals[$value['id']] = $total[0]['total'];
}
return view('drafts.search')->with('result', $result)->with('totals', $totals)->with('allArticles', $this->allArticles())->with('allCustomers', $this->allCustomers())->with('allUsers', $this->allUsers());
}
public function search(DraftSearchRequest $request) {
//Put request in session variable to use in view
$request1 = array('customer' => $request['customer'],'user' => $request['user'], 'reference' => $request['reference'], 'article' => $request['article']);
if ($request1['customer'] == "" && $request1['user'] == "" && $request1['reference'] == "" && $request1['article'] == "") {
session()->flash('draft_search_request', $request1);
}
else {
Session::put('draft_search_request', $request1);
}
return redirect ('drafts');
}
public function invoice(Request $request) {
//Create invoices for the selected drafts
//dd($request);
//dd($request->except('_token'));
$number_of_invoices = 0;
$draftdeleted = false;
$mail = false;
if (isset($request['mailThem']) && $request['mailThem'] == "on") {
$mail = true;
}
$invoicedate = $request['createDate'];
if (!checkdate(substr($invoicedate, 5, 2), substr($invoicedate, 8, 2), substr($invoicedate, 0, 4))) {
$invoicedate = "";
}
foreach($request->except('_token') as $key => $val) {
//dd($key);
if (substr($key, 0, 8) == "invoice_" && $val == "on") {
$draft_id = substr($key, 8);
// Create the invoice
// But only if there are lines
$draftheader = DraftHeader::findOrFail($draft_id)->toArray();
$draftlines = DraftHeader::findOrFail($draft_id)->lines()->get()->toArray();
if (count($draftlines) > 0) {
// Create the invoice header
$invoiceheader = InvoiceHeader::create($draftheader);
if ($invoicedate != "") {
$invoiceheader->created_at = $invoicedate;
$invoiceheader->save();
}
// Create the invoice lines
foreach ($draftlines as $draftline) {
$newline = new InvoiceLine;
$newline->article_id = $draftline['article_id'];
$newline->descr = $draftline['descr'];
$newline->qty = $draftline['qty'];
$newline->grossamount = $draftline['grossamount'];
$newline->discount = $draftline['discount'];
$newline->netamount = $draftline['netamount'];
$newline->taxrate = $draftline['taxrate'];
$newline->addition = $draftline['addition'];
$newline = $invoiceheader->lines()->save($newline);
}
// Delete the draft
DraftHeader::destroy($draft_id);
$number_of_invoices++;
if ($mail) {
// Add the invoice to the create and send queue (no recipient = to be processed)
$invoicemail = new InvoiceMail;
$invoicemail = $invoiceheader->mail()->save($invoicemail);
}
}
}
if (substr($key, 0, 7) == "delete_") {
// Delete the selected draft
$draft_id = substr($key, 7);
DraftHeader::destroy($draft_id);
session()->flash('flash_success', "Draft deleted");
$draftdeleted = true;
}
}
$andmailed = "";
if ($number_of_invoices > 0 && $mail) {
$andmailed = " and queued to be sent by mail";
}
if (!$draftdeleted) {
session()->flash('flash_success', $number_of_invoices . " invoice(s) created " . $andmailed);
}
$request1 = array('customer' => $request['customer'], 'user' => $request['user'], 'reference' => $request['reference'], 'article' => $request['article']);
if ($request1['customer'] == "" && ['user'] == "" && $request1['reference'] == "" && $request1['article'] == "") {
session()->flash('draft_search_request', $request1);
}
else {
Session::put('draft_search_request', $request1);
}
return redirect ('drafts');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create() {
return view('drafts.create')->with('allCustomers', $this->allCustomers());
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(DraftRequest $request) {
//dd($request);
// Get the customer information
/*
$this->validate($request, [
'reference' => 'required'
]);
*
*/
$customer = Customer::findOrFail($request['customer_id']);
$pass = array_merge($request->all(), $customer->toArray());
//dd($pass);
DraftHeader::create($pass);
//dd($request);
// Get the user information
/*
$this->validate($request, [
'reference' => 'required'
]);
*
*/
$user = User::findOrFail($request['user_id']);
$pass = array_merge($request->all(), $user->toArray());
//dd($pass);
DraftHeader::create($pass);
return redirect('drafts');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id) {
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id) {
// Retrieve header and lines
//dd($id);
$draftheader = DraftHeader::findOrFail($id)->toArray();
//dd($draftheader);
$draftlines = DraftHeader::findOrFail($id)->lines()->get()->toArray();
//dd($draftlines);
// Get the draft's total
$drafttotal = 0;
$drafttotal_in = 0;
foreach ($draftlines as $line) {
$drafttotal = $drafttotal + ($line['qty'] * $line['netamount']);
$drafttotal_in = $drafttotal_in + (($line['qty'] * $line['netamount']) / 100 * (100 + $line['taxrate']));
}
return view('drafts.edit')->with('header', $draftheader)->with('lines', $draftlines)->with('drafttotal', $drafttotal)->with('drafttotal_in', $drafttotal_in)->with('allArticles', $this->allArticles());
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id, DraftLinesRequest $request) {
//dd($request->all());
// Save the draft header (again)
$draftheader = DraftHeader::findOrFail($id);
if ($draftheader->reference != $request['reference']) {
$draftheader->reference = $request['reference'];
$draftheader->save();
}
// Update the lines if there are changes
$requestcopy = $request->All();
reset($requestcopy);
foreach ($requestcopy as $key => $value) {
if (substr($key, 0, 11) == "grossamount") {
$lineid = substr($key, 11);
$draftline = Draftline::findOrFail($lineid);
$v_descr = 'descr' . $lineid;
$v_qty = 'qty' . $lineid;
$v_grossamount = 'grossamount' . $lineid;
$v_discount = 'discount' . $lineid;
$v_addition = 'addition' . $lineid;
if ($draftline->descr != $request[$v_descr] || $draftline->qty != $request[$v_qty] || $draftline->grossamount != $request[$v_grossamount] || $draftline->discount != $request[$v_discount] || $draftline->addition != $request[$v_addition]) {
$draftline->descr = $request[$v_descr];
$draftline->qty = $request[$v_qty];
$draftline->addition = $request[$v_addition];
$draftline->grossamount = $request[$v_grossamount];
$draftline->discount = $request[$v_discount];
$draftline->netamount = $draftline->grossamount - ($draftline->grossamount * ($draftline->discount/100)) + ($draftline->grossamount * ($draftline->addition/100));
$draftline->save();
session()->flash('flash_success', 'Update succeeded');
}
}
}
// Check if a line needs to be deleted
reset($requestcopy);
foreach ($requestcopy as $key => $value) {
if (substr($key, 0, 6) == "cmdDel") {
$lineid = substr($key, 6);
$draftline = Draftline::findOrFail($lineid);
$draftline->delete();
session()->flash('flash_success', 'Draft line was deleted');
}
}
// Check if a new line should be created
if ($request['qty'] != 0 && $request['article_id'] > 0 && strlen($request['descr']) > 0) {
$newline = new DraftLine;
$article = Article::findOrFail($request['article_id']);
$customer = $draftheader->customer;
$newline->article_id = $request['article_id'];
$newline->descr = $request['descr'];
$newline->qty = $request['qty'];
$newline->grossamount = $article->gross;
$newline->discount = $customer->discount;
$newline->taxrate = $article->taxrate;
if ($customer->taxrate == "No tax") {
$newline->taxrate = 0;
}
$newline->netamount = $newline->grossamount - ($newline->grossamount * ($newline->discount/100));
$newline = $draftheader->lines()->save($newline);
session()->flash('flash_success', 'New draft line was added');
}
return redirect('drafts/' . $id . '/edit');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id) {
//
}
}
User model
<?php namespace App;
use App\Hour;
use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\Authenticatable;
use Sofa\Eloquence\Eloquence;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
use Notifiable;
use Eloquence;
public function draftheaders()
{
return $this->hasMany('App\DraftHeader');
}
protected $searchableColumns = ['name'];
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function hours()
{
return $this->hasMany(Hour::class);
}
}
User controller
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function find(Request $request)
{
$term = trim($request->q);
if (empty($term)) {
return \Response::json([]);
}
$users = user::search($term)->limit(5)->get();
$formatted_users = [];
foreach ($users as $user) {
$formatted_users[] = ['id' => $user->id, 'text' => $user->name];
}
return \Response::json($formatted_users);
}
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth')->except('find');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('user');
}
}
The database has the following tables:
User table,
Draftsheader table
In the draftsheader table I changed the column user_id to index. And
in the users table I changed column name to index. Normally I would
index the column and give it a foreignkey. But I looked at the
customer table and the draftsheader table and there where no
foreignkeys. So I was thinking maybe foreignkeys arent nessecary, as
long as the fields are indexed.
I hope you guys can help me out, cause i'm stuck... If information is missing let me now and I'll edit the page.
Update
In the view I changed [¨name¨] to [¨employee_name¨] Like suggested by a fellow stackoverflow user. It resulted in this:
Changed name to employee_name
Try changing this:
#foreach ($result as $draft)
<tr>
<td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
<td>{{ $draft['id'] }}</td>
<td>{{$draft['name'] }} ({{ $draft['user_id'] }})</td>
<td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
<td>{{ $draft['reference'] }}</td>
<td>{{ $draft['created_at'] }}</td>
<td></td>
<td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
<td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
</tr>
<?php $count++ ?>
#endforeach
To this:
#foreach ($result as $draft)
<tr>
<td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
<td>{{ $draft['id'] }}</td>
<td>{{$draft['employee_name'] }} ({{ $draft['user_id'] }})</td>
<td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
<td>{{ $draft['reference'] }}</td>
<td>{{ $draft['created_at'] }}</td>
<td></td>
<td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
<td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
</tr>
<?php $count++ ?>
#endforeach
You use ['name'] two times, but you have the customer_name on it.

Categories