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
Related
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!');
}
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
}
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.
I'm trying to set validation on my controller method, but on validation failure I'm getting error that method is not allowed http exception.
My controller:
namespace App\Http\Controllers\Web;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Services\InvoicesService;
class InvoiceController extends Controller
{
private $invoice;
public function __construct(InvoicesService $invoice) {
$this->invoice = $invoice;
}
public function startNewInvoice($id, $customer)
{
$ticket = $this->invoice->getTicketByInvoice($id);
$ticket = $ticket->Ticket;
return view('form', ['InvoiceId' => $id,'CustomerInfo' => $customer, 'records' => null, 'recordState' => null, 'ticket' => $ticket, 'invoices' => null]);
}
public function generateInvoice(Request $request)
{
//dd($request);
$this->validate($request, [
'CustomerNumber' => 'required|numeric'
]);
$invoiceId = $request->input('Invoice');
$customer = array('CustomerCode' => $request->input('CustomerNumber'),'CustomerName' => $request->input('CustomerName'),'CustomerAddress' => $request->input('CustomerAddress'),
'CustomerVATCode' => $request->input('CustomerVatNumber'));
$hash = $this->invoice->generateInvoice($invoiceId, $customer);
$newInvoice = $this->invoice->newInvoice($request->input('CustomerNumber'), $hash->Id);
return $this->startNewInvoice($newInvoice->Id, $customer);
}
}
Any help would be really appreciated
I have a problem when use Eloquent.
This is the error message.
Undefined property: Illuminate\Database\Eloquent\Collection::$refunds
This is My model.
class Beneficiary extends Eloquent {
public function refunds(){
return $this->hasMany('Refund');
}
}
class Refund extends Model {
protected $guarded = array();
public static $rules = array(
'request_id' => 'required',
'beneficiary_id' => 'required',
'concept' => 'required',
'date' => 'required | date_format:Y-m-d',
'amount' => 'required | min:-1 | numeric',
'deductible_amount' => 'required | numeric',
'max_applied' => 'required | numeric',
'yearly_balance' => 'required | numeric',
'payment_amount' => 'required | min:-1 | numeric',
'payment_date' => 'required | date_format:Y-m-d',
);
public function beneficiary(){
return $this->belongsTo('Beneficiary','beneficiary_id');
}
public function request(){
return $this->belongsTo('Models\Request','request_id');
}
}
And this is my Model.
class HomeController extends BaseController {
public function getIndex(){
$requests = Requisition::with(array(
'refunds' => function($refundsQuery){
$refundsQuery->with(array(
'beneficiary' => function($beneficiaryQuery){
$beneficiaryQuery->with(array('beneficiary', 'holder'));
}
));
},
'policy' => function($policyQuery){
$words=explode(' ',trim(Input::get('policy_code')));
$policyQuery->where('code','LIKE','%'.$words[0].'%');
for($i=1;$i<count($words);$i++){
$policyQuery->orWhere('code','LIKE','%'.$words[$i].'%');
}
},
'refunds' => function($refundsQuery){
$refundsQuery->with(array(
'beneficiary' => function($beneficiaryQuery){
$beneficiaryQuery->with(array('beneficiary','rut'));
}
));
}
));
if(Input::has('request_number')){
$words=explode(' ',trim(Input::get('request_number')));
$requests->where('number','LIKE','%'.$words[0].'%');
for($i=1;$i<count($words);$i++){
$requests->orWhere('number','LIKE','%'.$words[$i].'%');
}
}
if(Input::has('policy_code')){
$requests->whereHas('policy', function($policyQuery){
$words=explode(' ',trim(Input::get('policy_code')));
$policyQuery->where('code','LIKE','%'.$words[0].'%');
for($i=1;$i<count($words);$i++){
$policyQuery->orWhere('code','LIKE','%'.$words[$i].'%');
}
});
}
if(Input::has('rut')){
$person = Person::where('rut', Input::get('rut'))->get();
$beneficiary = Beneficiary::where('rut',Input::get('rut'))->get();
$refunds = $beneficiary->refunds; //Error
}
$requests = $requests->paginate(10);
return View::make('home.index',array(
'requests'=>$requests,
'policy_code' => Input::get('policy_code'),
'request_number' => Input::get('request_number'),
'rut' => Input::get('rut')
));
In this line occurs the error $refunds = $beneficiary->refunds;
Any idea?
When you do
$beneficiary = Beneficiary::where('rut',Input::get('rut'))->get();
Contains a Collection of models, not a Model, so you have to:
$beneficiaries = Beneficiary::where('rut',Input::get('rut'))->get();
foreach($beneficiaries as $beneficiary)
{
echo $beneficiary->refunds;
}
Or
$beneficiary = Beneficiary::where('rut',Input::get('rut'))->first();