i have a problem with saving data to database using LARAVEL - php

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
}

Related

Laravel - How to execute store resource?

I'm creating a CRUD app. But when I code in method store I have a problem: I'm trying to create a variable $contact = new Contact(). It's message: Undefined type 'App\Contact'.
This ContactController.php
use App\Contact;
....
public function store(Request $request)
{
$request->validate([
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required'
]);
$contact = new Contact([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name'),
'email' => $request->get('email'),
'job_title' => $request->get('job_title'),
'city' => $request->get('city'),
'country' => $request->get('country')
]);
$contact->save();
return redirect('/contacts')->with('success', 'Contact saved!');
}
I made it with this link: https://medium.com/techiediaries-com/laravel-7-crud-tutorial-build-a-crud-app-with-mysql-and-bootstrap-4-4ed8e94f2db0
Here are your option to create:
Option 1:
$contact = Contact::create([
'first_name' => $request->get('first_name')
]);
Option 2:
$contact = new Contact();
$contact->first_name = 'test';
$contact->save();
Also in your contact class, check your namespace. And, use the namespace in the controller as:
use App\Models\Contact; //since you said your contact.php is inside models folder
you keep controller simple and clean to use this
use App\Contact; // if use laravel 7
use App\Models\Contact // if use laravel 8
....
public function store(Request $request, Contact $contact)
{
$request->validate([
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required'
]);
$contact->create($request->all());
return redirect('/contacts')->with('success', 'Contact saved!');
}
in function update
use App\Contact;
....
public function update(Request $request, Contact $contact)
{
$id = $contact->id; // if use Route resource
$id = $request->id; // if use Route Post
$request->validate([
'first_name'=> 'required',
'last_name'=>'required',
'email'=>'required'
]);
$date = $request->except(['_token','_method']);
$contact->where('id', $id)->update($date);
return redirect('/contacts')->with('success', 'Contact updated!');
}

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

i want to insert refferal_code value in users table with laravel register api

register function look like this..
this function works but refferal_code not inserting
i'm sending values with postman
first_name, last_name, email, phone, password, c_password, refferal_code
public function register(Request $request, User $user)
{
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'phone' => 'required',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['result'=>'false','error'=>$validator->errors()], 401);
}
else{
$data = $request->all();
$chars = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ";
$res = $chars[mt_rand(10, strlen($chars)-1)].rand().$chars[mt_rand(10, strlen($chars)-1)];
$data['refferal_code'] = $res;
$data['password'] = bcrypt($data['password']);
//print_r($data);exit;
$user->create($data);
$success['token'] = $user->createToken('MyApp')-> accessToken;
$success['first_name'] = $user->first_name;
return response()->json(['result'=>'true', 'success'=>'User created.'], $this-> successStatus);
}
}
I think your model doesn't have refferal_code in his $fillable array. Can you check it ?
If you don't want to have problems with this, try using it in your User model
protected $fillable = [];
protected $guarded = ['id'];

Laravel saving data to two locations

I'm working on a larvel project where the user can create appointments. In addition I've created another model called clients so when a user creates an appointment the users "client" data is saved.
In my appointments controller I have the following: -
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
//create appointment
$apt = new Appointment;
$apt->name = $request->input('name');
$apt->user_id = auth()->user()->id;
$apt->save();
//create client
$client = new Client;
$client->first_name = $request->input('name');
$client->user_id = auth()->user()->id;
$client->save();
return redirect('/appointments')->with('success', 'Appointment created');
}
When saving the data it works and stores the data in the clients table however I know this isn't the cleanest way of saving the data, but what is the "laravel" way of doing this?
There's nothing wrong with your code. It's totally fine keeping it that way.
I prefer to say Model::create() to create models in one statement.
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
Appointment::create([
'name' => request('name'),
'user_id' => auth()->id()
]);
Client::create([
'first_name' => request('name'),
'user_id' => auth()->id,
]);
return redirect('/appointments')->with('success', 'Appointment created');
}
You can also use tap() function:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
tap(Appointment::create(['name' => request('name'), 'user_id' => auth()->id()]), function ($newAppoinment) {
Client::create([
'first_name' => $newAppoinment->name,
'user_id' => auth()->id,
]);
});
return redirect('/appointments')->with('success', 'Appointment created');
}
Or the best approach could be using model events:
class Appointment extends Model
{
public static function boot()
{
parent::boot();
static::created(function ($appointment) {
Client::create([
'user_id' => $appoinment->user_id,
'first_name' => $appoinment->name,
])
});
}
}

laravel route resource update method

I'm work on create to-do app in laravel with JWt
all method (index,store,show ..etc) in route resource works well except update
in result its work well and get success response but its not change in database
** sorry my english is not good
this is my short codes
api.php
Route::middleware('jwt.auth')->group(function () {
Route::resource('/todo', 'API\TodoController');
});
BaseController.php
class BaseController extends Controller
{
public function sendResponse($result,$message)
{
$response=[
'success'=> true,
'date' => $result,
'message'=> $message
];
return response()->json($response,200);
}
public function sendError($error,$errorMessages=[],$code=404)
{
$response=[
'success'=> false,
'message'=> $error
];
if (!empty($errorMessages)) {
$response['date']=$errorMessages;
}
return response()->json($response,$code);
}}
TodoController.php
class TodoController extends BaseController
{
.
.
.
public function update(Request $request, Todolist $todolist)
{
//
$input = $request->all();
$validator = Validator::make($input, [
'title' => 'required | max:255',
'content' => 'required | max:255',
'status' => 'required | max:2',
'start_date' => 'required ',
'end_date' => 'required ',
]);
if ($validator->fails()) {
return $this->sendError('error validation', $validator->errors());
}
$todolist->title = $request->title;
$todolist->content = $request->content;
$todolist->status = $request->status;
$todolist->start_date = $request->start_date;
$todolist->end_date = $request->end_date;
$todolist->save();
return $this->sendResponse($todolist->toArray(), 'update successfully');
}}
this is results in postman
https://i.stack.imgur.com/4oHqC.png
You should refer Model before class
use App\Todolist;
class TodoController extends BaseController
{
.
.
.
public function update(Request $request, Todolist $todolist)
{
//
$input = $request->all();
$validator = Validator::make($input, [
'title' => 'required | max:255',
'content' => 'required | max:255',
'status' => 'required | max:2',
'start_date' => 'required ',
'end_date' => 'required ',
]);
if ($validator->fails()) {
return $this->sendError('error validation', $validator->errors());
}
$todolist->title = $request->title;
$todolist->content = $request->content;
$todolist->status = $request->status;
$todolist->start_date = $request->start_date;
$todolist->end_date = $request->end_date;
$todolist->save();
return $this->sendResponse($todolist->toArray(), 'update successfully');
}}
TodoList.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Todolist extends Model
{
//
protected $table='todolists';
protected $fillable =[
'title',
'content',
'status',
'photo_id',
'date_id',
'start_date',
'end_date',
'user_id'
];
}
todo table
https://i.stack.imgur.com/GGr5Q.png

Categories