Laravel pivot table crud view information - php

I am creating a laravel application. Now i have to use a Pivot table. but i cant show the information from the other table. The create function works fine.
I just want to show the 'name' row of the 2nd table.
Table 1 (file):
table 2 (subfolder):
pivot table:
Controller:
public function index()
{
$files = File::with('subfolders')->get();
$subfolders = Subfolder::all();
$languages = Language::all();
$tags = Tag::all();
$users = User::all();
$roles = Role::all();
dd($files);
return view('admin.file.index', compact('files', 'subfolders', 'languages', 'tags', 'users', 'roles' ));
}
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'description_short' => '',
'description_long' => '',
'file' => 'mimes:pdf,xlsx,docx,pptx',
]);
if ($request->file) {
//dd($request);
$file = $request->file->getClientOriginalName();
$file_name = $file . '.' . $request->file->extension();
$document = new File([
'title' => $request->get('title'),
'description_short' => $request->get('description_short'),
'description_long' => $request->get('description_long'),
'file' => 'storage/files/' . $file_name,
]);
$request->file->move(public_path('storage/files/'), $file_name);
} else {
$document = new File([
'title' => $request->get('title'),
'description_short' => $request->get('description_short'),
'description_long' => $request->get('description_long'),
'file' => $request->get('file'),
]);
}
$document->save();
$document->subfolders()->attach($request->get('subfolder_id'));
return back();
}
index.blade:
#foreach($files as $file)
<tr>
<td>{{$file->id}}</td>
<td>{{$file->title}} </td>
<td>{{$file->description_short}} </td>
<td>{{$file->description_long}} </td>
<td>{{$file->file}}</td>
<td>{{#$file->subfolder->name}} </td>
<td>
i just need to show information thru the pivot table, but i have no idea how to

Related

undefined variable in view using dompdf

I am trying to generate a pdf with DOMPDF. This is my code:
class PDFController extends Controller
{
public function invoice(Request $request) {
// $institution = $this->institution();
// $user = $this->user();
$invoice = array($this->invoice_form($request));
$pdf = PDF::loadView('pdf-generation.invoice', $invoice);
return $pdf->setPaper('a4', 'landscape')->download('invoice.pdf');
//return view('pdf-generation.invoice')->with(['institution' => $institution, 'user' => $user, 'invoice' => $invoice]);
}
public function institution() {
$institution = Institution::where('id', 1)->get()->first();
return $institution;
}
public function user() {
$user = Auth::user();
return $user;
}
public function invoice_form(Request $request) {
$this->validate($request, array(
'furnizor-select' => 'required',
'document-number' => 'required',
'document-date' => 'required',
'due-date' => 'required',
'discount-procent' => 'required',
'discount-value' => 'required',
'total-value' => 'required',
'nir-number' => 'nullable'
));
$invoice = new \App\Models\Invoice();
$invoice->provider_id = $request->input('furnizor-select');
$invoice->number = $request->input('document-number');
$invoice->document_date = $request->input('document-date');
$invoice->due_date = $request->input('due-date');
$invoice->discount_procent = $request->input('discount-procent');
$invoice->discount_value = $request->input('discount-value');
$invoice->total = $request->input('total-value');
$invoice->save();
$invoices = Invoice::all();
$invoice_id = $invoices->last()->id;
$old_date = $request->input('document-date');
$new_date = date("d-m-Y", strtotime($old_date));
$provider_id = $request->input('furnizor-select');
$provider = Provider::where('id', $provider_id)->get();
$invoice_number = $request->input('document-number');
$old_due_date = $request->input('due-date');
$new_due_date = date("d-m-Y", strtotime($old_due_date));
$filename = 'pdfs/nir'.$invoice_id.'.pdf';
$institution = $this->institution();
$user = $this->user();
$array = array(
'invoice_id' => $invoice_id,
'new_date' => $new_date,
'provider' => $provider,
'invoice_number' => $invoice_number,
'due_date' => $new_due_date,
'provider' => $provider,
'institution' => $institution,
'user' => $user
);
return (object) $array;
}
}
And in my pdf-generation.invoice view, I have some html generate but it is not worth to post it all, so I am going to post only one line to give you some idea about the problem:
<span style="font-weight: bold; float: left;">{{$invoice->institution}}</span>
However, it says Undefined variable $invoice.. what could be the problem?
You can compact your variable like this:
$pdf = PDF::loadView('pdf-generation.invoice', compact('invoice'));

How can I store barcode inside validate request in Laravel

I have a code on the store function where I save product details. However, the barcode always return empty. I don't know how to save it with Product::create($data);'. Can I ask some direction?
$data = new Product;
$data->name = $request->name;
Do I need to save one by one on an object such as the one above?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
use Picqer;
class ProductsController extends Controller
{
public function index() {
$products = Product::orderBy('id')->get();
return view('products.index', compact('products'));
}
public function show(Product $product) {
return view('products.show', ['product' => $product]);
}
public function create() {
$products = Product::all();
return view('products.create', compact('products'));
}
public function edit(Product $product) {
return view('products.edit', compact('product'));
}
public function update(Request $request, Product $product) {
$request->validate([
'code' => 'required',
'barcode' => 'required',
'name' => 'required',
'description' => 'required|string|max:250',
'unit' => 'required|int',
'cost' => 'required',
'srp' => 'required',
'supplier' => 'required|string|max:250',
'quantity_left' => 'required',
'category' => 'required|string|max:250',
'delivered_date' => 'required|date',
'expiration_date' => 'required|date'
]);
$product->code = $request->code;
$product->barcode = $request->barcode;
$product->name = $request->name;
$product->description = $request->description;
$product->unit = $request->unit;
$product->cost = $request->cost;
$product->srp = $request->srp;
$product->supplier = $request->supplier;
$product->quantity_left = $request->quantity_left;
$product->category = $request->category;
$product->delivered_date = $request->delivered_date;
$product->expiration_date = $request->expiration_date;
$product->save();
return redirect()->route('products.index');
}
public function store(Request $request) {
$code = $request->code;
$generator = new Picqer\Barcode\BarcodeGeneratorHTML();
$barcode = $generator->getBarcode($code, $generator::TYPE_CODE_128);
$data = $request->validate([
'code' => 'required',
'barcode' => 'max:15|nullable',
'name' => 'required',
'description' => 'required|string|max:250',
'unit' => 'required|int',
'cost' => 'required',
'srp' => 'required',
'supplier' => 'required|string|max:250',
'quantity_left' => 'required',
'category' => 'required|string|max:250',
'delivered_date' => 'required|date',
'expiration_date' => 'required|date'
]);
Product::create($data);
return redirect()->route('products.index')->with('success', 'Product has been added!');
}
public function destroy(Product $product) {
$product->delete();
return back();
}
}
I think I just missed something. I've used this framework: https://github.com/picqer/php-barcode-generator
You need to overwrite the barcode coming from request with the one you generated.
$product = new Product();
$product->name = 'some name';
...
$product->barcode = $barcode;
$product->save();
I made this work by merging the two arrays:
$data = array_merge($data, ['barcode' => $barcode]);
Product::create($data);

Laravel - propery does not exist on this collection instance

So I have a small Laravel car project and I have two separate tables, cars table and vehicle_infos table.
Here is my CarsController#store:
public function store(Request $request)
{
$this->validate($request, [
'naslov' => 'required',
'marka' => 'required',
'model' => 'required',
/*
'kubikaza' => 'required',
'zamajac' => 'required',
'potrosnja' => 'required',
'karoserija' => 'required',
'kilometraza' => 'required',
'godiste' => 'required',
'gorivo' => 'required',
'vlasnistvo' => 'required',
'kilovata' => 'required',
'konjska_snaga' => 'required',
'emisiona_klasa' => 'required',
'pogon' => 'required',
'mjenjac' => 'required',
'br_brzina_mjenjaca' => 'required',
'velicina_felni' => 'required',
'posjeduje_gume' => 'required',
'br_vrata' => 'required',
'br_sjedista' => 'required',
'str_volana' => 'required',
'klima' => 'required',
'boja_spolj' => 'required',
'boja_unutrasnj' => 'required',
'materijal_unutrasnj' => 'required',
'registracija' => 'required',
'ostecenje' => 'required',
'zamjena' => 'required',
'sigurnost' => 'required',
'oprema' => 'required',
'stanje' => 'required',
'nacin_finansiranja' => 'required',
'nacin_prodaje' => 'required',
'cijena' => 'required',
'vrsta_cijene' => 'required',
'opis_oglasa' => 'required',
//'fotografije' => 'required',
//'kontakt' => 'required',
*/
]);
/*
// Handle File Upload
if($request->hasFile('fotografije')){
// Get filename with the extension
$filenameWithExt = $request->file('fotografije')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('fotografije')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('fotografije')->storeAs('public/slike_oglasa', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
*/
$images=array();
if($files=$request->file('fotografije')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move('slike_oglasa',$name);
$images[]=$name;
}
}
$car = new Car;
$car->naslov = $request->input('naslov');
$car->marka = $request->input('marka');
$car->model = $request->input('model');
$car->kubikaza = $request->input('kubikaza');
$car->zamajac = $request->input('zamajac');
//$car->potrosnja = $request->input('potrosnja');
$car->karoserija = $request->input('karoserija');
$car->godiste = $request->input('godiste');
$car->kilometraza = $request->input('kilometraza');
$car->gorivo = $request->input('gorivo');
$car->vlasnistvo = $request->input('vlasnistvo');
$car->kilovata = $request->input('kilovata');
$car->konjska_snaga = $request->input('konjska_snaga');
$car->emisiona_klasa = $request->input('emisiona_klasa');
$car->pogon = $request->input('pogon');
$car->mjenjac = $request->input('mjenjac');
$car->br_brzina_mjenjaca = $request->input('br_brzina_mjenjaca');
$car->velicina_felni = $request->input('velicina_felni');
$car->posjeduje_gume = $request->input('posjeduje_gume');
$car->br_vrata = $request->input('br_vrata');
$car->br_sjedista = $request->input('br_sjedista');
$car->str_volana = $request->input('str_volana');
$car->klima = $request->input('klima');
$car->boja_spolj = $request->input('boja_spolj');
$car->boja_unutrasnj = $request->input('boja_unutrasnj');
$car->materijal_unutrasnj = $request->input('materijal_unutrasnj');
$car->registracija = $request->input('registracija');
$car->ostecenje = $request->input('ostecenje');
$car->zamjena = $request->input('zamjena');
$car->sigurnost = implode(',', $request->input('sigurnost'));
$car->oprema = implode(',', $request->input('oprema'));
$car->stanje = implode(',', $request->input('stanje'));
$car->nacin_finansiranja = $request->input('nacin_finansiranja');
$car->nacin_prodaje = $request->input('nacin_prodaje');
$car->cijena = $request->input('cijena');
$car->vrsta_cijene = $request->input('vrsta_cijene');
$car->opis_oglasa = $request->input('opis_oglasa');
//$car->user_id = 1;
$car->user_id = auth()->user()->id;
$car->fotografije = implode("|", $images);
$car->trajanje_oglasa = $request->input('trajanje_oglasa');
$car->placeni_status = $request->input('placeni_status');
if($car->trajanje_oglasa == 30){
$car->to_datum_isteka = Carbon::now()->addDays(30);
} else {
$car->to_datum_isteka = Carbon::now()->addDays(60);
}
if($car->placeni_status == 0){
$car->po_datum_isteka = Carbon::now();
} else if($car->placeni_status == 1) {
$car->po_datum_isteka = Carbon::now()->addDays(7);
} else if($car->placeni_status == 2) {
$car->po_datum_isteka = Carbon::now()->addDays(14);
} else if($car->placeni_status == 3) {
$car->po_datum_isteka = Carbon::now()->addDays(21);
}
//$car->kontakt = $request->input('kontakt');
$car->save();
$vehicleinfo = new VehicleInfo;
//$vehicleinfo->urban = "Urban";
$vehicleinfo->car_id = $car->id;
$vehicleinfo->save();
//ukupno oglasa od strane usera, skladistenje u ads table
$ad = new Ad;
$ad->car_id = $car->id;
//$ad->user_id = 1;
$ad->user_id = auth()->user()->id;
$ad->save();
return redirect('/cars');
}
My model Car.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Car extends Model
{
protected $table = "cars";
protected $primaryKey = "id";
protected $fillable = [
'naslov', 'marka', 'model', 'kubikaza', 'zamajac', 'karoserija', 'godiste', 'kilometraza', 'br_brzina_mjenjaca',
'gorivo', 'vlasnistvo', 'kilovata', 'konjska_snaga', 'emisiona_klasa', 'pogon', 'mjenjac', 'br_vrata', 'velicina_felni', 'posjeduje_gume',
'br_sjedista', 'str_volana', 'klima', 'boja_spolj', 'boja_unutrasnj', 'materijal_unutrasnj', 'registracija', 'ostecenje',
'zamjena', 'sigurnost', 'oprema', 'stanje', 'nacin_finansiranja', 'nacin_prodaje', 'cijena', 'vrsta_cijene', 'opis_oglasa', 'fotografije'
];
public function user(){
return $this->belongsTo(User::class);
}
public function vehicleinfo(){
return $this->hasMany(VehicleInfo::class);
}
public function ad(){
return $this->hasMany(Ad::class);
}
}
My model VehicleInfo.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class VehicleInfo extends Model
{
protected $table = 'vehicle_infos';
protected $primaryKey = 'id';
protected $fillable = ['car_id', 'urban', 'extra_urban', 'combined', 'length', 'width', 'height'];
public function car(){
return $this->belongsTo(Car::class);
}
}
So my car_id from vehicle_infos table is coming from public function store() of the CarsController and it automatically storing new data in vehicle_infos and that is okay.
But when I do php artisan tinker to check my relations it shows me error. So here is what I do in php artisan tinker:
First step: $car = App\Car::find(4); and it shows me all data for that car, then $car->vehicleinfo and it shows me all data from vehicle_infos table with car_id of 4.
But when I do $car->vehicleinfo->urban ,for example, it shows me this error Exception with message 'Property [urban] does not exist on this collection instance.'. What do I do wrong? Please help me it frustating.
Basing from the structure of your model, cars has many vehicleinfo. Doing $cars->vehicleinfo will give you a collection instance since it hasMany of it. Doing $car->vehicleinfo->urban will not work since there is no urban property on a collection instance.
Try doing:
$cars->vehicleinfo->first()->urban;
Or if you want all the urban properties of all the related vehicle infos:
$cars->vehicleinfo->pluck('urban') // returns an array of all the urban properties found
See Laravel Collections for more methods.
Hello can you try to replace find() by find()->first() or replace $car->vehicleinfo->urban by $car->vehicleinfo[´urban’]
And my eyes see this line urban is commented is normal the collection of instance urban not exist if you push data with the line commented. Normally sql will gold you you’re column urban is required no ?
This line have comment for urban
`
$vehicleinfo = new VehicleInfo;
//$vehicleinfo->urban = "Urban";
$vehicleinfo->car_id = $car->id;
$vehicleinfo->save(); `

How do I unit-test table filter function in lumen

This is the my back-end code. I wrote the test for this function as follows:
public function index(Request $request)
{
$fields = 'in:' . implode(',', Schema::getColumnListing('suppliers'));
$messages = [
'order_by.in' => 'The selected column name is invalid.',
];
$this->validate($request, [
'page' => ['numeric'],
'per_page' => ['numeric'],
'order_direction' => ['in:desc,asc,DESC,ASC'],
'order_by' => [$fields],
], $messages);
$perPage = 10;
$filter = '';
$orderBy = 'id';
$orderDirection = 'DESC';
try {
if ($request->has('per_page')) $perPage = (int)$request->per_page;
if ($request->has('filter')) $filter = $request->filter;
if ($request->has('order_by')) $orderBy = $request->order_by;
if ($request->has('order_direction')) $orderDirection = strtoupper($request->order_direction);
$suppliers = Supplier::select('id', 'firstname', 'lastname', 'phone', 'email', 'custom_field_1', 'custom_field_2')->where('store_id', Auth::user()->store);
if (!!$filter) {
$suppliers->where('id', 'LIKE', "%{$filter}%")
->orWhere('firstname', 'LIKE', "%{$filter}%")
->orWhere('lastname', 'LIKE', "%{$filter}%")
->orWhere('email', 'LIKE', "%{$filter}%")
->orWhere('phone', 'LIKE', "%{$filter}%");
}
$suppliers->orderBy($orderBy, $orderDirection);
$suppliers = $suppliers->paginate($perPage);
return response()->json([
'success' => true,
'data' => $suppliers->toArray(),
], Response::HTTP_OK);
} catch (Exception $e) {
report($e);
return serverExceptionMessage();
}
}
This is what I have tried and test. I'm creating a store because store_id is a foreign key in my supplier table and adding suppliers dynamically and filtering the firstname through the URL and getting the result from seeJson as an array:
public function testSupplierListViewPaginationFilterTest()
{
$user = factory('App\Models\User')->make();
$store = (factory('App\Models\Store')->make())->getAttributes();
$this->actingAs($user)
->post('/create-new-store', $store)
->seeStatusCode(Response::HTTP_OK);
$attributes = [
'id' => 1,
'firstname' => 'ashid',
'lastname' => 'mhd',
'phone' => 776358547,
'email' => 'ashid#email.com',
'custom_field_1' => 'test',
'custom_field_2' => 'test',
];
$user->store = Store::latest()->first()->id;
$attributes['store_id'] = Auth::user()->store;
$supplier = Supplier::create($attributes);
$this->actingAs($user)
->get('/suppliers?filter=' . $supplier['firstname'], $attributes)
->seeStatusCode(Response::HTTP_OK)->seeJson([
'success' => true,
"data" =>
[
'id' => 1,
'firstname' => 'ashid',
'lastname' => 'mhd',
'phone' => 776358547,
'email' => 'ashid#email.com',
'custom_field_1' => 'test',
'custom_field_2' => 'test',
]
]);
}
I'm getting following error:
1) SupplierTest::testSupplierListViewPaginationFilterTest
Unable to find JSON fragment
["data":"custom_field_1":"test","custom_field_2":"test","email":"ashid#email.com","firstname":"ashid","id":1,"lastname":"mhd","phone":776358547}] within [{"data":{"current_page":1,"data":[{"custom_field_1":"test","custom_field_2":"test","email":"ashid#email.com","firstname":"ashid","id":1,"lastname":"mhd","phone":"776358547"}],"first_page_url":"http:\/\/localhost\/suppliers?page=1","from":1,"last_page":1,"last_page_url":"http:\/\/localhost\/suppliers?page=1","next_page_url":null,"path":"http:\/\/localhost\/suppliers","per_page":10,"prev_page_url":null,"to":1,"total":1},"success":true}].
Failed asserting that false is true.
I need a best solution for this problem .

Too few arguments to function App\Http\Controllers\MyControllers\GameController::update(), 2 passed and exactly 3 expected

I get this error when I try to update my posts
In form everything is correct I guess, because I haven't changed anything there.
Thats my form method:
<form method="post" action="{{ route('games.update', $game->id) }}">
#method('PATCH')
#csrf
</form>
This is my update method:
everything was working but suddenly it started giving this error
public function update(Request $request, $id, Game $game)
{
if ($game->author !== auth()->user()->id || auth()->user()->cannot('edit games'))
abort(404);
$request->validate([
'title' => 'required',
'type' => 'required',
'city' => 'required',
'district' => 'required',
'comment' => 'required',
'full_comment' => 'required',
'photo' => 'sometimes|mimes:jpeg,jpg,gif,bmp,png',
]);
$game = Game::find($id);
$game->title = $request->get('title');
$game->type = $request->get('type');
$game->city = $request->get('city');
$game->district = $request->get('district');
$game->comment = $request->get('comment');
$game->full_comment = $request->get('full_comment');
if ($request->has('photo')) {
$photoName = $game->id . '_photo' . time() . '.' . request()->photo->getClientOriginalExtension();
$game->photo = $request->get('photo');
$game->photo = $photoName;
$request->photo->storeAs('game-photos', $photoName);
}
$game->save();
return redirect('/games')->with('success', 'Game has been updated');
}
Should work like this:
public function update(Request $request, $id)
{
$request->validate([
'title' => 'required',
'type' => 'required',
'city' => 'required',
'district' => 'required',
'comment' => 'required',
'full_comment' => 'required',
'photo' => 'sometimes|mimes:jpeg,jpg,gif,bmp,png',
]);
$game = Game::find($id);
$game->title = $request->get('title');
$game->type = $request->get('type');
$game->city = $request->get('city');
$game->district = $request->get('district');
$game->comment = $request->get('comment');
$game->full_comment = $request->get('full_comment');
if ($game->author !== auth()->user()->id || auth()->user()->cannot('edit games')) {
abort(404);
}
if ($request->has('photo')) {
$photoName = $game->id . '_photo' . time() . '.' . request()->photo->getClientOriginalExtension();
$game->photo = $request->get('photo');
$game->photo = $photoName;
$request->photo->storeAs('game-photos', $photoName);
}
$game->save();
return redirect('/games')->with('success', 'Game has been updated');
}
Remove the 3rd formal parameter called
Game $game
If you don’t have route model binding implementation on the Game model

Categories