I am a beginner in laravel. I was updating records but I can't figure out what is wrong with my $student->save();
My controller code is as follows
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;
use PHPUnit\Framework\MockObject\Builder\Stub;
class HomeController extends Controller
{
public function read() {
$students = Student::all();
return view('read',['Students'=>$students]);
}
public function insert() {
return view('insert');
}
public function insertPost(Request $req) {
$student=new Student();
$student->Name = $req->input('name');
$student->Marks = $req->input('marks');
$student->save();
return redirect('/');
}
public function update($id) {
$student = Student::find($id);
return view('update',['Student'=>$student]);
}
public function delete($id) {
$student = Student::find($id);
$student->delete();
}
public function updatePost(Request $req) {
$student = Student::find($req->input('id'));
$student->Name=$req->input('name');
$student->Marks=$req->input('marks');
$student->save();
// Student::where('ID',$req->input('id'))
// ->update(['Name'=>$req->input('name'),
// 'Marks'=>$req->input('marks')]);
return redirect('/');
}
}
The Main main in updatePost(); is causing the records not updating
$student = Student::find($req->input('id'));
$student->Name=$req->input('name');
$student->Marks=$req->input('marks');
$student->save();
I changed the way of updating records to
Student::where('ID',$req->input('id'))
->update(['Name'=>$req->input('name'),
'Marks'=>$req->input('marks')]);
and it worked. But I wanted to know at which part I was making mistake in it.
You need to set your primary key to 'ID'
By default the primary key or PK name is 'id'
But in your code it changed to 'ID'
So you need to go to your User.php model class
and add this line
public $primaryKey = 'ID';
One thing you can try is using Laravel's update method. update will handle the save internally.
$student = Student::findOrFail($req->input('id')));
$student->update([
'Name' => $req->input('name'),
'Marks' => $req->input('marks'),
]);
Related
I want to create a laravel crud repository for a model. The model has 1 1:n and 1 n:n relationship.
class Product extends Model
{
protected $table = 'products';
protected $fillable = [
'description', 'merchantId', 'name', 'link', 'pictureUrl', 'ean', 'brand', 'aktPrice', 'affiliatePortal', 'programId'
];
public function prices() {
return $this->hasMany(Price::class);
}
public function categories() {
return $this->hasMany(Categorie::class);
}
}
Now I want to create a repository which has a save method and a controller for a restapi, which calls the save methode. My question is how should a save method looks that the entity is saved correctly and which mapping operations have to be done before that it works. I hope someone can help me and send me a save method, or a crud repository for my case and can help me to design the controller.
A Controller, with all the crud operations, look like this:
<?php
namespace App\Http\Controllers;
use App\Models\Room;
use Illuminate\Http\Request;
class RoomController extends Controller
{
public function index()
{
$rooms = Room::all()->toArray();
return $rooms;
}
public function add(Request $request)
{
$room = new Room;
$room->create($request->all());
return response()->json('The room successfully added');
}
public function getById($id)
{
$room = Room::find($id);
return response()->json($room);
}
public function update($id, Request $request)
{
$room = Room::find($id);
$room->update($request->all());
return response()->json('The room successfully updated');
}
public function delete($id)
{
$room = Room::find($id);
$room->delete();
return response()->json('The room successfully deleted');
}
}
I've got the following function in a migration file. The migration is to add a new column, and then update the columns of the existing entries:
<?php
private function updatePlans()
{
$plans = PlanProvider::query()->get();
foreach ($plans as $plan) {
$plan->num_adults = 1;
if (stripos($plan->rate_name, 'couple') !== false) {
$plan->num_adults = 2;
}
$plan->save();
}
}
Now, what's happening here is that when I call save(), it's updating EVERY model, instead of the one inside the loop. I have a similar function for another migration, and it works as expected. Why would this update every model rather than just the one?
$plans is a Collection that contains all your "plans".
Your $plan->save(); is outside your if conditions, so obviously it updates every single row, no matter if it has 1 or 2 num_adults
public function store(Request $request)
{
$this->validate($request,[
'email' => 'required|email|unique:subscribers'
]);
$subscriber = new Subscriber();
$subscriber->email = $request->email;
$subscriber->save();
Toastr::success('You are Successfully Added Our Subscriber List:)','Success');
return redirect()->back();
}
you can try this
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PlanProvider extends Model
{
protected $table = 'plan_provider';
protected $guarded = [];
public $timestamps = false;
}
private function updatePlans()
{
$plans = PlanProvider::findOrFail(id);
$plans->num_adults = 1;
$plans->save();
return redirect()->back();
}
I'm trying Laravel 5.4 (i usually work with 5.1) and im actually copypasting most of the code, so i dont understand what is the trouble, maybe is because there is a better way to do it but yeah, its been 1 hour and i cant get past this;
Hope you can help me with this..
In case this isn't enough i'll be posting my views and routes. Thank to everyone.
This is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $fillable = ['user_id', 'user_name', 'user_birthday'];
public static $rules = [
'user_name' => 'required|max:255',
'user_birthday' => 'required'
];
public $timestamps = false;
}
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UsersController extends Controller
{
public function index()
{
$users = User::with('user_id')->orderBy('user_id', 'ASC')->paginate(10);
return view('admin.users.index')->with("user", $users);
}
public function create()
{
return view('admin.users.create');
}
public function store(Request $request)
{
$users = new User($request->all());
$users->save();
return redirect()->route('admin.users.index');
}
public function show($id)
{
$users = User::find($id);
}
public function edit($id)
{
$users = User::find($id);
return view('admin.users.edit')->with('user', $user);
}
public function update(Request $request, $id)
{
$users = User::find($id);
$users->user_name = $request->user_name;
$users->user_birthday = $request->user_birthday;
$users->save();
return redirect()->route('admin.users.index');
}
public function destroy($id)
{
$users = User::find($id);
$users->delete();
return redirect()->route('admin.users.index');
}
}
Your error is from the following line of code. When you use with on a model is to load children relationships or sub-models. That is why the application is looking for the relationship user_id in the User Model thinking that it's a sub-model of the User model but it's not, so it return an error.
wrong
$users = User::with('user_id')->orderBy('user_id', 'ASC')->paginate(10);
correct
$users = User::orderBy('user_id', 'ASC')->paginate(10);
I'm building an API, i'm getting the following error while updating and deleting from table i'm using postman to test my api
//update error
QueryException in Connection.php line 770:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: update `lessons` set `title` = , `body` = , `completed` = , `updated_at` = 2017-01-03 09:14:10 where `id` = 11)
//delete error
FatalErrorException in LessonsController.php line 80:
Call to a member function delete() on null
My controller LessonsController
<?php
namespace App\Http\Controllers;
use Response;
use App\lesson;
use Illuminate\Http\Request;
use App\Acme\Transformers\LessonTransformer;
use Illuminate\Support\Facades\Input;
class LessonsController extends ApiController {
protected $lessonTransformer;
function __construct(LessonTransformer $lessonTransformer) {
$this->lessonTransformer = $lessonTransformer;
}
//fetch all and pass a metadata 'data'
public function index() {
$lessons = Lesson::all();
return $this->respond([
'data' => $this->lessonTransformer->transformCollection($lessons->all())
]);
}
//fetch by id
public function show($id) {
$lesson = Lesson::find($id);
if(! $lesson) {
return $this->respondNotFound();
}
return $this->respond([
'data' => $this->lessonTransformer->transform($lesson)
]);
}
public function store() {
if (! input::get('title') or ! input::get('body')) {
return $this->respondBadRequest();
}
Lesson::create(input::all());
return $this->respondCreated();
}
public function update(Request $request, $id) {
$ulesson = Lesson::find($id);
$ulesson->title = $request->input('title');
$ulesson->body = $request->input('body');
$ulesson->completed = $request->input('completed');
$ulesson->save();
return "Sucess updating user #" . $ulesson->id;
}
public function destroy(Request $request) {
$dlesson = Lesson::find($request->input('id'));
$dlesson->delete();
return "Employee record successfully deleted #" . $request->input('id');
}
}
my model Lesson
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Lesson extends Model
{
protected $fillable = ['title', 'body', 'completed',];
//protected $hidden =['title'];
}
the store and other functions are working fine
Thank You
In update
can you dd($request->input('title')) in line 69
I think you don't sent the value of title
and in delete
I think you have no value in id field
Please check you postman and set it like this
i just downloaded Insomnia and tested every thing is working fine as expected
i don't know why it's not working in postman though
Laravel APi Update Function...
According to this query no need to define keys
Controller Function
`
public function update(Request $request){
$reqdata = $request->all();
$reqdata['date_created'] = date('Y-m-d');
$lesson= Lesson::where('id',$request->id)->update($reqdata);
if ($lesson) {
return 'true';
}else{
return 'false';
}
} `
Your data type as attached image
For some reason I can't save to the database. No errors, just nothing updating. I know the commands are correctly working, because returning the $user afterwards gives me the respective fields modified. But somewhere the information isn't getting put into the database.
The blade can be found here: http://pastebin.com/8bAEsjtj
The request form can be found here: http://pastebin.com/ZCD1Xvjn
This is the controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\UserFormRequest;
use App\UserEdit;
use DB;
use App\Http\Requests;
class EditUserController extends Controller
{
public function index()
{
$array = UserEdit::all()->toArray();
return view('UserEntry', compact('array'));
}
public function create()
{
//
}
public function store()
{
//
}
public function show($ID)
{
try {
$array = UserEdit::findorFail($ID)->toArray();
return view('UserEdit')->with('array', $array);
} catch(\Exception $e) {
return \Redirect::route('users.index')
->withMessage('This user does not exist');
}
}
public function edit(UserEdit $user)
{
return view('EditUser', compact('user'));
}
public function update(UserFormRequest $request, UserEdit $user)
{
//$input->$request->all();
//$user->fill(Input::all());
$user->fill([
'name' => $request->get('name'),
'email' => $request->get('email'),
'First_Name' => $request->get('First_Name'),
'Last_Name' => $request->get('Last_Name')
]);
//$user->name = Input::get('name');
//$user->email = Input::get('email');
//$user->First_Name = Input::get('First_Name');
//$user->Last_Name = Input::get('Last_Name');
$user->save();
//$user->save();
// return redirect()->route('users.index')->with('message', 'Details Updated!');
return $user;
}
public function destroy($id)
{
//
}
}
Pretty sure that's all above board, so why wouldn't it work? Am I missing some detail somewhere? This is the model: http://pastebin.com/vJBzfUVu
Ok. Found the answer, there's a difference between how mysql and php handle the 'id' in a database table.
In this instance, because I've inherited the database from other devs, the id column was capitalised.
This probably made the php laravel generates throw an error as it was looking for 'id' and didn't find anything.
I didn't notice this because it didn't actually print that error, and my other code was accounting for the capitalisation.
Changing the ID to id and fixing the references in my code seems to have solved the problem.