Laravel - propery does not exist on this collection instance - php

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

Related

Method Illuminate\Support\Collection::save does not exist

I want to create update function, but the error keep shown. Is it because of the join query or the get() or first() method. I dont know how to solve this.
Method Illuminate\Support\Collection::save does not exist.
Controller:
public function update(Request $request, $id)
{
// dd($request);
$request->validate([
'first_name' => 'max:150',
'last_name' => 'max:150',
'userD_ic' => 'max:12',
'userD_position' => 'max:50',
'userD_epf' => 'max:20',
'userD_socso' => 'max:20',
'userD_passport' => 'max:30',
'user_id' => 'numeric',
'ea_serial_no' => 'required|numeric',
'ea_employer_id' => 'required|numeric',
'ea_employee_income_tax_no' => 'required|numeric',
'ea_lhdn_branch' => 'required|max:255',
]);
$eaforms = DB::table('ea')
->join('users', 'ea.user_id', '=', 'users.id')
->join('user_details', 'ea.user_id', '=', 'user_details.user_id')
->where('ea.id', $id)
->select('ea.*', 'users.first_name', 'users.last_name', 'user_details.userD_position', 'user_details.userD_ic', 'user_details.userD_passport', 'user_details.userD_epf', 'user_details.userD_socso')
->get();
$eaforms->first_name = $request->first_name;
$eaforms->last_name = $request->last_name;
$eaforms->userD_ic = $request->userD_ic;
$eaforms->userD_position = $request->userD_position;
$eaforms->userD_epf = $request->userD_epf;
$eaforms->userD_socso = $request->userD_socso;
$eaforms->userD_passport = $request->userD_passport;
$eaforms->user_id = $request->user_id;
$eaforms->ea_serial_no = $request->ea_serial_no;
$eaforms->ea_employer_id = $request->ea_employer_id;
$eaforms->ea_employee_income_tax_no = $request->ea_employee_income_tax_no;
$eaforms->ea_lhdn_branch = $request->ea_lhdn_branch;
$eaforms->save();
return redirect()->route('ea.view', $eaforms->id)->with('update', 'add');
}
Model:
class EaForms extends Model
{
protected $table = 'ea';
use HasFactory, SoftDeletes;
protected $fillable = [
'user_id',
'ea_year',
'ea_serial_no',
'ea_employer_id',
'ea_employee_income_tax_no',
'ea_lhdn_branch',
'created_at',
'updated_at',
'deleted_at',
];
public function users()
{
return $this->belongsTo(User::class);
}
}
Can you try this (With your relationship method called users)
$eaforms = EaForms::where('id',$id)->first();
// Update user data
$eaforms->first_name = $request->first_name;
$eaforms->last_name = $request->last_name;
$eaforms->userD_ic = $request->userD_ic;
$eaforms->userD_position = $request->userD_position;
$eaforms->userD_epf = $request->userD_epf;
$eaforms->userD_socso = $request->userD_socso;
$eaforms->userD_passport = $request->userD_passport;
// Update EA Forms
$eaforms->users->user_id = $request->user_id;
$eaforms->users->ea_serial_no = $request->ea_serial_no;
$eaforms->users->ea_employer_id = $request->ea_employer_id;
$eaforms->users->ea_employee_income_tax_no = $request->ea_employee_income_tax_no;
$eaforms->users->ea_lhdn_branch = $request->ea_lhdn_branch;
$eaforms->users->save();
$eaforms->save();

i have a problem with saving data to database using LARAVEL

this is all my codes after cliking on button doesn't save to database i try to change method of saving but not work
use App\makereservations;
use Illuminate\Http\Request;
class reservationController extends Controller
{
public function hreservation()
{
return view('hreservation');
}
public function reserve (Request $request)
{
$this->validate($request ,[
'name' => 'required',
'email' => 'required',
'phone' => 'required|email',
'date' => 'required',
'time' => 'required',
]);
$reservation = new makereservations();
$reservation = $request->input('name');
$reservation = $request->input('email');
$reservation = $request->input('phone');
$reservation = $request->input('date');
$reservation = $request->input('time');
$reservation = $request->input('personne');
$reservation -> statu = false;
$reservation -> save();
return redirect()->back();
}
}
this is the roote
route::post('reserve', 'reservationController#reserve' )->name('reserv.sent');
You missed the -> arrow sign.
$reservation = new makereservations();
$reservation->name = $request->input('name');
$reservation->email = $request->input('email');
$reservation->phone = $request->input('phone');
$reservation->date = $request->input('date');
$reservation->time = $request->input('time');
$reservation->personne = $request->input('personne');
$reservation-> statu = false;
$reservation-> save();
return redirect()->back();
If in the MakeReservations model you have massively assignable fields
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class makereservations extends Model
{
protected $table = "your_table_name"
...
protected $fillable = [
'name', 'email', 'phone', 'date', 'time', 'personne', 'status'
];
...
}
Your reserve method in reservationController it may be so:
<?php
namespace App\Http\Controllers;
use App\makereservations;
use Illuminate\Http\Request;
class reservationController extends Controller
{
...
public function reserve (Request $request)
{
$this->validate($request ,[
'name' => 'required',
'email' => 'required|email',
'phone' => 'required',
'date' => 'required',
'time' => 'required',
]);
$inputs = $request->all();
$inputs['status'] = false;
$reservation = makereservations::create($inputs);
return redirect()->back();
}
}
I have detected that in your validation method you are trying to validate that the phone is an email
You can do it more shortly and in a clean way, to optimize your code.
public function reserve (Request $request)
{
$attributes = $this->validate($request ,[
'name' => 'required',
'email' => 'required|email',
'phone' => 'required',
'date' => 'required',
'time' => 'required',
'personne' => ''
]);
$attributes['statu'] = false;
makereservations::create($attributes);
return redirect()->back();
}
In your model make sure these things
class makereservations extends Model
{
protected $table = 'reservation';
protected $guarded = []; //it means all data from request will be mass assignable
}

php - Call to a member function getClientOriginalName() on null and remove alert laravel

I am newbie in Laravel so i really need some help. I want to ask when
I commented the part 'photo' => required why if I update without entering the photo it shows some error like call to a member function getClientOriginalName() on null. So the real question is I want to update without entering photo and it should still to be updated.
This is my code in Controller to upload photo
public function update($id, UpdateBannerRequest $request)
{
$input = $request->all();
//get original file name
$filename = Input::file('photo')->getClientOriginalName();
$input['photo'] = $filename;
Input::file('photo')->move($this->path, $filename);
$banner = $this->BannerRepository->findWithoutFail($id);
if (empty($banner)) {
Flash::error('Banner not found');
return redirect(route('banner.index'));
}
$banner = $this->BannerRepository->update($input, $id);
Flash::success('Banner updated successfully.');
return redirect(route('banner.index'));
}
This is the code on my model
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Banner extends Model
{
use SoftDeletes;
public $table = 'banners';
protected $dates = ['deleted_at'];
public $fillable = [
'title',
'description',
'photo',
'status'
];
protected $casts = [
'title' => 'string',
'description' => 'string',
'photo' => 'string',
'status' => 'integer'
];
public static $rules = [
'title' => 'required',
'description' => 'required',
//'photo' => 'required',
'status' => 'required'
];
}
$validator = Validator::make(
$request->all(),
array(
'photo' => 'required',
),
array(
'photo' => 'Please choose file',
)
);
If Photo is not mandatory directly use this
if(!empty($request->photo)){
//do something
}
else{
Flash::error('Banner not provided');
return redirect(route('banner.index'));
}
Hope this will help.. let me know if any issue..Thank you
your update function would look like
public function update($id, UpdateBannerRequest $request)
{
$input = $request->all();
$banner = $this->BannerRepository->findWithoutFail($id);
if(!empty($request->photo)){
//do something for saving the name of file in database and other value respectively using
// $filename = Input::file('photo')->getClientOriginalName();
// $banner->photo = $filename;
}
else{
Flash::error('Banner not provided');
return redirect(route('banner.index'));
}
$banner->save();
Flash::success('Banner updated successfully.');
return redirect(route('banner.index'));
}
The simplest validation required would be to test if Input::hasFile('photo'), this should be placed before you call Input::file('photo')->getClientOriginalName()
if( Input::hasFile('photo') == false )
{
Flash::error('Banner not provided');
return redirect(route('banner.index'));
}
https://laravel.com/docs/4.2/requests#files
You should check bellow code.
if(isset(Input::file('photo'))
Before work with it.

Use of undefined constant while storing data from form

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

Is it possible to access two models from a single function of a controller in Laravel4?

So I'm trying to insert values into two tables from a single form using Laravel4.
this is my Store() function.Am i doing it right..?
I know i should be using two controllers AddressController.php and PeopleController.php.., but can i use a single controller to insert into two tables using a single form.?
public function store()
{
$rules = array(
'address_id' => 'required',
'contact_id' => 'required',
'prefix' => 'required',
'firstname' => 'required',
'middlename' => 'required',
'lastname' => 'required',
'suffix' => 'required',
'occupation' => 'required',
'gender' => 'required',
'comment' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
$user= Auth::user();
if (!empty($user->id))
$user_id=$user->id;
// process the login
/*if ($validator->fails()) {
return Redirect::to('people/create')
->withErrors($validator);
} else {*/
// store
$person = new Person;
$person->user_id=$user_id;
$person->address_id =Input::get('address_id');
//$person->contact_id = Input::get('contact_id');
$person->prefix = Input::get('prefix');
$person->firstname =Input::get('firstname');
$person->middlename =Input::get('middlename');
$person->lastname =Input::get('lastname');
$person->suffix =Input::get('suffix');
$person->occupation =Input::get('occupation');
$person->gender =Input::get('gender');
$person->comment =Input::get('comment');
//$person->user_id =Input::get('user_id');
$person->save();
$validator = Validator::make($data = Input::all(), Address::$rules);
$address->address1 = Input::get('address1');
$address->address2 = Input::get('address2');
$address->apt = Input::get('apt');
$address->city = Input::get('city');
$address->state = Input::get('state');
$address->zip = Input::get('zip');
$address->country = Input::get('country');
$address->save();
// redirect
Session::flash('message', 'Successfully created new Employee!');
//return Redirect::to('addresses/create');
return Response::json($person);
}
As long as you've defined a relationship between the person and address models, then you can use the person model's push() method which is designed to save multiple related models in a single step
Note that if you had fillable defined for your models, you could also eliminate a lot of those boilerplate $person->prefix = Input::get('prefix'); statements from your code as well

Categories