Use of undefined constant while storing data from form - php

I have created a model
Review.php
and resource controller for it
ReviewController.php
with route
Route::resource('review','ReviewController');
and created a form to get the values. My store method:
public function store(Request $request)
{
$this->validate($request, [
'fullname' => 'required|max:255',
'email' => 'required',
'country' => 'required',
'tourname' => 'required',
'content' => 'required'
]);
$reviews = new Review;
$reviews->name = $request->fullname;
$reviews->email = $request->email;
$reviews->country = $request->country;
$reviews->content = $request->content;
$reviews->tour_id = $request->tourname;
if($request->hasFile('clidentpp')){
$image = $request->file('clidentpp');
$filename = time().'.'.$image->getClientOriginalName();
$location = public_path('images/client_review'.$filename);
Image::make($image)->resize(128, 128)->save($location);
$reviews->path = $location;
}
$reviews->save();
Session::flash('success','Thank you for your review !');
return back()->withInput(['tab'=>'complete']);
}
I'm getting error
Use of undefined constant reviews - assumed 'reviews'
pointing at line $reviews = new Review;. I tried changing$reviews to $review also still no luck.

It should be $reviews = new Review();

Try this.
$review[] = '';
$review['name'] = $request->fullname;
$review['email'] = $request->email;
...
Review::create($review);

Related

Undefined variable in laravel 9

I'm creating a user registration form. I create a form in the Component. when the user registers he redirects to the user page where he sees all users. when he wanted to edit or update something from in his details he redirects to the same registration form page but this will be a new URL and new Title. I'm getting an undefined variable $title and $url error. when I pass data from the controller to view I get this error.
Registration Form Controller
public function create(Request $request)
{
$url = url('/register');
$title = ("Registration Form");
$data = compact( 'url');
return view('RegistrationForm')->with($data);
}
public function store (Request $request)
{
$request->validate(
[
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required|email',
'password' => 'required',
'confirm_password' => 'required|same:password|min:8',
'address' => 'required',
'country' => 'required',
'state' => 'required',
'city' => 'required',
'gender' => 'required',
'tearms_and_conditions' => 'required',
],
[
'firstname.required' => 'Please enter your First Name',
'lastname.required' => 'Please nter your Last Name',
'email.required' => 'Please enter an Email',
'password.required' => 'Please Enter a Password'
],
);
$users = new Users;
$users->firstname = $request['firstname'];
$users->lastname = $request['lastname'];
$users->email = $request['email'];
$users->password = md5($request['password']);
$users->address = $request['address'];
$users->country = $request['country'];
$users->state = $request['state'];
$users->city = $request['city'];
$users->gender = $request['gender'];
$users->date_of_birth = $request['date_of_birth'];
$users->save();
return redirect('/register/view');
}
public function view (Request $request)
{
$users = Users::all();
$data = compact('users');
return view('user-view')->with($data);
}
public function delete($id)
{
$user = Users::find($id);
echo "<pre>";
print_r ($user);
die;
return redirect('/register/view');
}
public function edit($id)
{
$user = Users::find($id);
if (is_null($user))
{
return redirect('/register/view');
}
else
{
$url = url("user/update"."/". $id);
$title = "Update Details";
$data = compact('user', 'url', 'title');
return redirect('/register')->with($data);
}
}
public function update($id, Request $request)
{
$user = Users::find($id);
$users->firstname = $request['firstname'];
$users->lastname = $request['lastname'];
$users->email = $request['email'];
$users->address = $request['address'];
$users->country = $request['country'];
$users->state = $request['state'];
$users->city = $request['city'];
$users->gender = $request['gender'];
$users->date_of_birth = $request['date_of_birth'];
$users->save();
return redirect('register/view');
}
}
Route
Route::get('/register', [RegistrationFormController::class, 'index']);
View
<body>
<h1> {{$title}} </h1>
<x-registration-form-component :country="$country" :url="$url" />
RegisreationFormComponent
You have to pass the $data variable as the second argument of the view() method:
public function index ()
{
$url = url('/register');
$title = "Registration Form";
$data = compact('title', 'url');
return view('RegistrationForm', $data);
}
First, to answer your question:
When you use the compact method, you are placing those values in an array. You would need to call them like so:
{{ $data['title'] }}
{{ $data['url'] }}
However, you could clean the code up a little bit like this:
public function index()
{
return view('RegistrationForm', [
'url' => url('/register'),
'title' => 'Registration Form',
]);
}
You can then use them in the blade file like so:
{{ $url }}
{{ $title }}

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(); `

Creating default object from empty value laravel

I've been getting the error Creating default object from empty value laravelI was successful to insert new rows with the following code but today when I tried testing the code it is returning the error pointing on the line $reviw->rating = $request->productrating;.
Structure of my db table is:
id|fname|lname|email|country|title|content|rating|thumbnail|tour_id|status
public function store(Request $request)
{
// dd($request->all());
$this->validate($request, [
'fname' => 'required',
'lname' => 'required',
'email' => 'required',
'country' => 'required',
'title' => 'required|min:10',
'productrating' => 'required',
'content' => 'required|min:10'
]);
// dd($request->productrating);
$review = new Review;
$review->fname = $request->fname;
$review->lname = $request->lname;
$review->email = $request->email;
$review->country = $request->country;
$review->title = $request->title;
$review->content = $request->content;
$reviw->rating = $request->productrating;
if($request->hasFile('fileupload1')){
$image = $request->file('fileupload1');
$filename = 'thumb'.time().'.'.$image->getClientOriginalExtension();
$location = 'images/client_review/'.$filename;
Image::make($image)->resize(200, 200)->save($location);
$review->thumbnail = $location;
}
$review->tour_id = $request->product_id;
$review->status = false;
$review->save();
Session::flash('success','Thank You for submitting us your review.');
return view('public.pages.message-review');
}
I'm sending following data from the form to save into the table.
I think you need to update your code like :
$review = new Review;
$review->fname = $request->fname;
$review->lname = $request->lname;
$review->email = $request->email;
$review->country = $request->country;
$review->title = $request->title;
$review->content = $request->content;
$review->rating = $request->productrating;
You have an error in $reviw->rating = $request->productrating; change $reviw to $review and it will work

How do you query twice using two different models in laravel?

I have in my controller a function like this.
$validator = Validator::make($request->all(), [
'user_id' => 'required|numeric',
'role' => 'required',
'firstname' => 'required',
'middlename' => '',
'lastname' => 'required',
'phone_no' => 'required|digits:11',
'address' => 'required',
'city' => 'required',
'state' => 'required',
'bio' => 'required',
]);
if ($validator->fails()) {
return $validator->errors();
}
Then I have the first update query (using model) like this:
$user = User::find($request->user_id);
$user->firstname = $request->firstname;
$user->middlename = $request->middlename;
$user->lastname = $request->lastname;
$user->phone_no = $request->phone_no;
The second one follows like this:
if($request->role == 'customer' ){
$userInfo = Customer::where('user_id', $request->user_id);
$userInfo->address = $request->address;
$userInfo->city = $request->city;
$userInfo->state = $request->state;
$userInfo->bio = $request->bio;
}elseif($request->role == 'employer' ){
$userInfo = Employer::where('user_id', $request->user_id);
$userInfo->address = $request->address;
$userInfo->city = $request->city;
$userInfo->state = $request->state;
$userInfo->bio = $request->bio;
}
if($user->save() && $userInfo->save()){
return response(array("status" => "success", 'statusCode' => 200, 'message' => 'Your Profile Was Updated'))->header('Content-Type', 'application/json');
}
I used AJAX to send the data to the controller. But when I click the update button it displays this error:
BadMethodCallException in Builder.php line 2451:
Call to undefined method Illuminate\Database\Query\Builder::save()
I keep getting this error. How do I resolve this?
Change the following. Also check if userinfo exists before saving since you have a condition where it might not.
$userInfo = Customer::where('user_id', $request->user_id)->first();
$userInfo = Employer::where('user_id', $request->user_id)->first();
if($user->save() && (isset($userInfo) && $userInfo->save())){}
Also your code can be refactored to reduce half the stuff you do. But that's out of scope for this question.
Call to undefined method Illuminate\Database\Query\Builder::save() results because you're calling the save() function on the builder rather than a collection. This is because you're not actually executing your query.
$userInfo = Employer::where('user_id', $request->user_id);
Should be
$userInfo = Employer::where('user_id', $request->user_id)->first();
save() method can save changes in one Eloquent object.
You dont have in $userInfo variable Eloquent object. Just calling where on Model does not return Eloquent object.
Change
$userInfo = Customer::where('user_id', $request->user_id)->first();
$userInfo = Employer::where('user_id', $request->user_id)->first();

Categories