Array to string conversion using laravel 6 - php

i added some fields to users table of laravel auth, and when i want to create a new user it gives me error Call to a member function hasFile () on array.
RegisterController.php
protected function create(array $data)
{
$jdate = Carbon::now();
//image
if($data->hasFile('image'))
{
$image = $data->file('image');
$imagee = Crypt::encryptString($image);
$image->storeAs("public\annonces\\".$jdate->format('F').$jdate->year,$imagee.'.'.$image->extension());
$data->image = "annonces\\".$jdate->format('F').$jdate->year."\\".$imagee.'.'.$image->extension();
}
//images
$dataim = array();
if($data->hasFile('images'))
{
foreach($data->file('images') as $file)
{
$namee = "public\\annonces\\".$jdate->format('F').$jdate->year."\\".time().'.'.$file->extension();
$name = Crypt::encryptString($namee).'.'.$file->extension();
$file->storeAs("public\\annonces\\".$jdate->format('F').$jdate->year, $name);
array_push($dataim,$name);
}
}
$data->images=json_encode($dataim);
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'telephone' => $data['telephone'],
'ville' => $data['ville'],
'ighrem' => $data['ighrem'],
'autrei' => $data['autrei'] ?? null,
'hay' => $data['hay'],
'autreh' => $data['autreh'] ?? null,
'adressem' => $data['adressem'],
'adresser' => $data['adresser'],
'image' => $data['image'] ?? null,
'images' => $data['images'] ?? null
]);
}

May you use as below
protected function create(Request $data){}

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

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 to delete old avatar after uploading new on laravel?

I was trying to delete old avatar after uploading new avatar. Just I couldn't find solution. I am new to laravel5, Could you help me? I am using a project from github. please look at "munafio cubetalk" on github. maybe I need to change something more. It doesn't delete user avatar also when user deletes his account.
public function s_general(Request $request){
$this->validate($request,[
'username' => 'required|min:3|max:50',
'avatar' => 'nullable|image|mimes:jpeg,png,jpg|max:1024',
'fullname' => 'required',
'email' => 'required|email'
]);
if ($request['username'] == Auth::user()->username &&$request['fullname'] == Auth::user()->name && $request['email'] == Auth::user()->email && !$request->hasFile('avatar')) {
return redirect()->back()->with('general_msg', Lang::get('trans.noChanges_MSG'));
}else{
$avatar = $request->file('avatar');
if ($request->hasFile('avatar')) {
$avatar_ext = $avatar->getClientOriginalExtension();
$avatar_name = rand(9,999999999)+time().".".$avatar_ext;
$avatar_new = $avatar->storeAs("avatar",$avatar_name);
}else{
$avatar_name = Auth::user()->avatar;
}
$update_general = User::where('uid',Auth::user()->uid)->update(['username' => $request['username'],'name' => $request['fullname'], 'email' => $request['email'],'avatar' => $avatar_name]);
return redirect()->back()->with('general_msg', Lang::get('trans.changes_saved'));
}
}
You can use laravel delete method to do that, make sure you import use Illuminate\Support\Facades\Storage; top of your controller class.
public function s_general(Request $request){
$this->validate($request,[
'username' => 'required|min:3|max:50',
'avatar' => 'nullable|image|mimes:jpeg,png,jpg|max:1024',
'fullname' => 'required',
'email' => 'required|email'
]);
if ($request['username'] == Auth::user()->username &&$request['fullname'] == Auth::user()->name && $request['email'] == Auth::user()->email && !$request->hasFile('avatar')) {
return redirect()->back()->with('general_msg', Lang::get('trans.noChanges_MSG'));
}else{
$avatar = $request->file('avatar');
if ($request->hasFile('avatar')) {
// update your code in here
$avatar_name = Auth::user()->avatar;
Storage::delete($avatar_name);
$avatar_ext = $avatar->getClientOriginalExtension();
$avatar_name = rand(9,999999999)+time().".".$avatar_ext;
$avatar_new = $avatar->storeAs("avatar",$avatar_name);
}else{
$avatar_name = Auth::user()->avatar;
}
$update_general = User::where('uid',Auth::user()->uid)->update(['username' => $request['username'],'name' => $request['fullname'], 'email' => $request['email'],'avatar' => $avatar_name]);
return redirect()->back()->with('general_msg', Lang::get('trans.changes_saved'));
}
}
Finally I solved it.
I post my edited code. If someone needs help later.
public function s_general(Request $request){
$this->validate($request,[
'username' => 'required|min:3|max:50',
'avatar' => 'nullable|image|mimes:jpg,jpeg|max:1024',
'fullname' => 'required',
'location' => 'max:255',
'bio' => 'max:340',
'email' => 'required|email'
]);
if ($request['username'] == Auth::user()->username &&$request['fullname'] == Auth::user()->name && $request['location'] == Auth::user()->location && $request['bio'] == Auth::user()->bio && $request['email'] == Auth::user()->email && !$request->hasFile('avatar')) {
return redirect()->back()->with('general_msg', Lang::get('trans.noChanges_MSG'));
}else{
$avatar = $request->file('avatar');
$user = Auth::user();
$uid = Auth::user()->uid;
$oldavatar = '/storage/avatar/'.$user->avatar;
if ($request->hasFile('avatar')) {
Storage::delete('$oldavatar');
$avatar_ext = $avatar->getClientOriginalExtension();
$avatar_name = $uid.".".$avatar_ext;
$avatar_new = $avatar->storeAs("avatar",$avatar_name);
}else{
$avatar_name = Auth::user()->avatar;
}
$update_general = User::where('uid',Auth::user()->uid)->update(['username' => $request['username'],'name' => $request['fullname'], 'bio' => $request['bio'], 'location' => $request['location'], 'email' => $request['email'],'avatar' => $avatar_name]);
return redirect()->back()->with('general_msg', Lang::get('trans.changes_saved'));
}

Laravel insert into new form, with existing users

I've created a new form for existing users.
And i'm trying to insert the new values into the database, but the values wont save.
public function editUser(Request $request, $id, $check)
{
$curID = $id;
$userData = $request->input();
$curUser = User::Where('id', $curID)->first();
$address = Address::where('id', $userData['address_id']);
------Not working----------------
if(empty($curUser->$address)){
$curUser->insert($address)([
'address_id' => $address->id,
'region_id' => $userData['region'],
'country_id' => $userData['country'],
'city_id' => $userData['city'],
'street_name' => $userData['street_name'],
'house_number' => $userData['house_number'],
'postcode' => $userData['postcode']
]);
-------Not working----------------
} else{
$address->update([
'region_id' => $userData['region'],
'country_id' => $userData['country'],
'city_id' => $userData['city'],
'street_name' => $userData['street_name'],
'house_number' => $userData['house_number'],
'postcode' => $userData['postcode'],
]);
return redirect('client')->with($this->messageBag, "User edited!");
}
public function editUser(Request $request, $id, $check)
{
$user = User::where('id',$id)->first();
$address = Address::where('id',$request->input('address_id'))->first();
if(empty($address)){
$address=new Address();
}
$address=$this->saveData($address,$request()->all());
$user->update(['address_id'=>$address->id]);
return redirect('client')->with($this->messageBag, "User edited!");
}
protected function saveData(Address $address,array $userData){
$address->region_id= $userData['region'];
$address->country_id= $userData['country'];
$address->city_id= $userData['city'];
$address->street_name= $userData['street_name'];
$address->house_number= $userData['house_number'];
$address->postcode= $userData['postcode'];
$address->save();
return $address;
}

cannot insert to another table after register

i want to insert into userbio after register here is my register RegisterController
protected function create(array $data)
{
$databio = new ModelBio();
$maxbio = $databio->getMaxbioId();
// die( $maxbio );
return User::create([
'username' => $data['username'],
'email' => $data['email'],
'biodataId' => $maxbio,
'password' => bcrypt($data['password']),
]);
return Biodata::create([
'biodataId' => $maxbio,
'fullname' => $data['fullname']
]);
}
It creates new record for Users. But, there is a problem i cant insert into usersbio, I can't find any error message there . Btw RegisterController is from laravel auth. here is my Biodata
class Biodata extends Model
{
//
protected $primaryKey = 'biodataId';
protected $table = "usersbio";
public $incrementing = false;
protected $fillable = [
'biodataId','address','fullname','remarks'
];
static function getMaxbioId(){
$max = Biodata::max('biodataId');
if($max == ""){
return "BIO-0001";
}else{
$number = substr($max, 4);
return 'BIO-' . sprintf('%04d', intval($number) + 1);
}
}
}
how can i fix it ? thanks in advance
Do not write return while creating User. It actually returns from there and no further code will be executed of the function.
protected function create(array $data)
{
$databio = new ModelBio();
$maxbio = $databio->getMaxbioId();
// die( $maxbio );
User::create([ // Removed `return` from here
'username' => $data['username'],
'email' => $data['email'],
'biodataId' => $maxbio,
'password' => bcrypt($data['password']),
]);
return Biodata::create([
'biodataId' => $maxbio,
'fullname' => $data['fullname']
]);
}

Categories