Call to a member function update() on null LARAVEL - php

I tried to update specific item but it was error 'Call to a member function update() on null'.
I tried to change ->update($data) with ->insert($data) before and it works.
Controller:
public function update(Request $request, $id)
{
$this -> validate($request, array(
'gamename' => 'required|min:3',
'price' => 'required|int|min:1',
'genre' => 'required',
'releaseddate' => 'required|date',
'picture' => 'required|mimes:jpeg,jpg,png,gif'
));
$gamename = $request->input('gamename');
$genre = $request->input('genre');
$price = $request->input('price');
$releaseddate = Carbon::parse($request->input('releaseddate'));
$picture = $request->file('picture')->getClientOriginalName();
$data=array('gamename' => $gamename, 'genre'=>$genre, 'price'=>$price,'releaseddate'=>$releaseddate,'picture'=>$picture );
DB::table('games')->join('genres', 'games.genreid', '=', 'genres.genreid')->find($id)->update($data);
return redirect('managegame');
}
View:
<form action="/update/{id}" method="post" id="registerform" enctype="multipart/form-data">
<div class="errorpop{{ $errors->has('genre') ? ' has-error' : '' }}">
<label for="genre" class="">Genre</label>
<div class="">
#foreach($genres as $genre)
<option value="{{ $genre->genreid }}">{{ $genre->genre }}</option>
#endforeach
#if ($errors->has('genre'))
<span class="help-block">
<strong>{{ $errors->first('genre') }}</strong>
</span>
#endif
</div>
</div>

{id} not a value. You must have value for {id} .
Example: action="/update/1"
<form action="/update/1" method="post" id="registerform" enctype="multipart/form-data">
<div class="errorpop{{ $errors->has('genre') ? ' has-error' : '' }}">
<label for="genre" class="">Genre</label>
<div class="">
#foreach($genres as $genre)
<option value="{{ $genre->genreid }}">{{ $genre->genre }}</option>
#endforeach
#if ($errors->has('genre'))
<span class="help-block">
<strong>{{ $errors->first('genre') }}</strong>
</span>
#endif
</div>
</div>
Then to update you use method where('id', $id) replace find($id)
DB::table('games')->join('genres', 'games.genreid', '=', 'genres.genreid')->where('id', $id)->update($data);
https://laravel.com/docs/5.5/queries#updates

Make sure you got the object
$game = DB::table('games')->
join('genres', 'games.genreid', '=', 'genres.genreid')->where('id',$id)->get();
//make sure you have the desired object.then
$game->update($data);

I'm nor sure this line works as you expect
DB::table('games')->join('genres', 'games.genreid', '=', 'genres.genreid')->find($id)->update($data);
What are you trying to update? games or genres ? You can't update 2 tables at once like that. You'd need to find the games row to update, update that that, and the joined table row, and update that, cannot do it all at once.
But the fact that you're trying to update 2 tables from one simple form, in the same method suggests that your tables is not properly laid out?

id)->update($data);
return redirect('managegame');
}
View:
has('genre') ? ' has-error' : '' }}">
Genre
<div class="">
#foreach($genres as $genre)
<option value="{{ $genre->genreid }}">{{ $genre->genre }}</option>
#endforeach
#if ($errors->has('genre'))
<span class="help-block">
<strong>{{ $errors->first('genre') }}</strong>
</span>
#endif
</div>
</div>

Related

Undefined variable: in Laravel

i can't get variable seat in form action at {!! Form::open(['action' => ['SeatController#book', $seat->id] , 'method' => 'POST'])!!} to working. here is my code:
blade.php:
#extends('layouts.app')
#section('content')
<br><br><br>
<h3>From {{$bus->departdest}} to {{$bus->arrivedest}}</h3>
<div> Date : {{$bus->date}}</div>
<div> Boarding Time : {{$bus->depart}}</div>
<div> Arrival Time : {{$bus->arrival}}</div>
<div> Plate Number : {{$bus->platenum}}</div>
<hr>
<img src="/images/seat.jpg" height="175.5px" width="521.5px" >
<hr>
<div> <h3>Available Seats : {{$bus->available}} </h3></div>
#if ($bus->available>0)
{!! Form::open(['action' => ['SeatController#book', $seat->id] , 'method' => 'POST'])!!}
#csrf
<div class="form-group row">
<label for="num" class="col-sm-4 col-form-label text-md-right">{{ __('Choose seat') }}</label>
<div class="col-md-12">
<select class="form-control{{ $errors->has('num') ? ' is-invalid' : '' }}" name="num">
#foreach($seats as $seat)
#if ($seat->bus_id == $bus->id && $seat->status == 0)
<option value="{{ $seat->id }}">{{ $seat->num }}</option>
#endif
#endforeach
</select>
#if ($errors->has('num'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('num') }}</strong>
</span>
#endif
</div>
</div>
<br>
{{Form::hidden('_method','POST')}}
{{Form::submit('Confirm', ['class' => 'btn btn-primary'])}}
Cancel
{!! Form::close() !!}
#else
<div> No available ticket </div>
Cancel
#endif
#endsection
BusController.php:
public function show($id){
$bus = Bus::find($id);
$user = Auth::user();
$seats = Seat::all();
return view('showseat')->with(compact('bus', 'user', 'seats'));
}
You might need to book a seat on the Bus? So here:
['SeatController#book', $seat->id]
Should be:
['SeatController#book', $bus->id]
You cannot use $seat there as you are passing $seats to the view, and you iterate to show the seat number in a select element.
Then in your book function you can still get the seat number using
$request->num // or request('num')
As num is the name attribute of your select field for the seat number.

Edit / Update database Laravel

I am struggling to update data in the database with an edit form and couldn't find anything online that fits the logic of my setup.
I have a add button, delete button and an edit button. Adding and Deleting works but Editing does not update the data.
Any help would be appreciated as I have tried multiple methods with no success.
Thank you in advance.
View:
#extends('layouts.app')
#section('content')
<div class="container flex-center">
<div class="row col-md-8 flex-column">
<h1>Edit a link</h1>
#foreach ($links as $link)
<form action="{{ url('link/'.$link->id) }}" method="POST">
{!! csrf_field() !!}
#method('PUT')
#if ($errors->any())
<div class="alert alert-danger" role="alert">
Please fix the following errors
</div>
#endif
<h3 class="edit-link-title">{{ $link->title }}</h3>
{!! csrf_field() !!}
<div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Title" value="{{ $link->title }}">
#if($errors->has('title'))
<span class="help-block">{{ $errors->first('title') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('url') ? ' has-error' : '' }}">
<label for="url">Url</label>
<input type="text" class="form-control" id="url" name="url" placeholder="URL" value="{{ $link->url }}">
#if($errors->has('url'))
<span class="help-block">{{ $errors->first('url') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('description') ? ' has-error' : '' }}">
<label for="description">Description</label>
<textarea class="form-control" id="description" name="description" placeholder="description">{{ $link->description }}</textarea>
#if($errors->has('description'))
<span class="help-block">{{ $errors->first('description') }}</span>
#endif
#endforeach
</div>
<button type="submit" class="btn btn-default submit-btn">Submit</button>
</form>
</div>
</div>
#endsection
web/route controller:
use Illuminate\Http\Request;
Route::post('/submit', function (Request $request) {
$data = $request->validate([
'title' => 'required|max:255',
'url' => 'required|url|max:255',
'description' => 'required|max:255',
]);
$link = tap(new App\Link($data))->save();
return redirect('/');
});
use App\Link;
Route::delete('/link/{link}', function (Link $link) {
// Link::destroy($link);
$link->delete();
return redirect('/');
});
Route::PUT('/link/{link}', function (Link $link) {
$link->update();
return redirect('/');
});
As a design pattern, it's often recommended to separate your controller from the routes. The reason your edit is not updating is that you're not providing the model with the data from the request:-
Route::PUT('/link/{link}', function (Request $request, Link $link) {
$request->validate([
'title' => 'required|max:255',
'url' => 'required|url|max:255',
'description' => 'required|max:255',
]);
$link->update($request->all());
return redirect('/');
});
In a controller, you could abstract away the validation logic to a validation helper function to avoid duplicating code.
Good luck!

Laravel: Display data in DropDown from database

I was developing a project with Laravel and want to use dropdownlist and populate it with data from database please help. Here is the code that I use:
Controller:
public function create()
{
$items = Income::pluck('name', 'id');
return view ('IncomeExpense.create');
}
View:
<div class="form-group">
{{Form::label('', 'Category')}}
{{Form::select('IncomeExpense',null, $items,['class'=>'form-control',
'placeholder'=>'Choose category'])}}
</div>
First of all,
you have an error in your controller... Please read the eloquent official documentation It should be:
public function create()
{
$items = Income::all();
return view ('IncomeExpense.create', compact('items'));
}
Anyway you should not use a form builder, I think it's much more usefull if you use the native blade features like Components & Slots. Form Builder have been removed from Laravel 5.0 if I rember correctly in order to focus the framework attention to the backend...
Heare a couple of example with Bootstrap 4:
Vanilla
<form method="POST" action="{{ route('your-route') }}" aria-label="{{ __('My form') }}">
#csrf
<div class="form-group row">
<label for="dropdown" class="col-sm-4 col-form-label text-md-right">{{ __('My dropdown') }}</label>
<div class="col-md-12">
<select class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="dropdown">
#foreach($my_collection as $item)
<option value="{{ $item->id }}">{{ $item->text }}</option>
#endforeach
</select>
#if ($errors->has('dropdown'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('dropdown') }}</strong>
</span>
#endif
</div>
</div>
{{-- other fields --}}
Components
<!-- /resources/views/components/select.blade.php -->
{{ $label }}
<div class="col-md-{{ $column == null ? 12 : $column }}">
<select class="form-control{{ ' ' . $select_css }}{{ $error == null ? '' : ' is-invalid' }}" name="dropdown">
#foreach($my_collection as $item)
<option value="{{ $item->id }}">{{ $item->text }}</option>
#endforeach
</select>
#if ($error != null)
<span class="invalid-feedback" role="alert">
<strong>{{ $error</strong>
</span>
#endif
</div>
<!-- /resources/views/my/form.blade.php -->
<form method="POST" action="{{ route('your-route') }}" aria-label="{{ __('My form') }}">
#csrf
<div class="form-group row">
#component('components.select', ['select_css' => 'whatever', 'my_collection' => $my_collection])
#slot('label')
<label for="dropdown" class="col-sm-4 col-form-label text-md-right">{{ __('My dropdown') }}</label>
#endslot
</div>
{{-- other fields --}}
Mirasan - You need to pass the view your information retrieved from the database.
$items = Income::pluck('name', 'id');
return view ('IncomeExpense.create')->with(compact('items'));
Then inside your blade file you will access the array 'items' (rather than $items).
Regards -

Select Selected value of a dropdown in laravel 5.4

I have a dropdown called designation, where a user will select one of it, and after submitting it, if there is some error then I want to select the selected designation.
I am using this in laravel 5.4.
Controller
$info = DB::table("designation")
->where('status','=',1)
->pluck("name","id");
return view('regUser.add',['check' => 'userList','designation' => $info]);
View Files
<div class="form-group {{ $errors->has('designation') ? ' has-error' : '' }}">
<label for="designation">Designation</label>
<select id="designation" name="designation" class="form-control">
<option value="">--- Select designation ---</option>
#foreach ($designation as $key => $value)
<option value="{{ $key }}" />{{ $value }}</option>
#endforeach
</select>
#if ($errors->has('designation'))
<span class="help-block">
<strong>{{ $errors->first('designation') }}</strong>
</span>
#endif
</div>
Now if the validator found some error then I want to select the previously selected one.
How can i achive this in laravel 5.4.
After submiting the form it comes to addUserInformation function, where I validate the user information which have this piece of code
public function addUserInformation(Request $request){
$this->validate($request, [
'name' => 'required|string|min:5',
'email' => 'required|string|email|unique:users,email',
'designation' => 'required|exists:designation,id',
'password' => 'required|min:6',
'confirm_password' => 'required|same:password',
'userimage' => 'required|image',
]);
$selectedID = $request->input('designation');
}
Larvel passes the inputs back on validation errors. You can use the old helper function to get the previous values of form. A simple comparison should do the trick.
<div class="form-group {{ $errors->has('designation') ? ' has-error' : '' }}">
<label for="designation">Designation</label>
<select id="designation" name="designation" class="form-control">
<option value="">--- Select designation ---</option>
#foreach ($designation as $key => $value)
<option value="{{ $key }}" {{ old('designation') == $key ? 'selected' : ''}}>{{ $value }}</option>
#endforeach
</select>
#if ($errors->has('designation'))
<span class="help-block">
<strong>{{ $errors->first('designation') }}</strong>
</span>
#endif
</div>
You have to maintain the state of old input by using return redirect() like:
return redirect('form')->withInput();
Retrieving Old Data
To retrieve flashed input from the previous request, use the old method on the Request instance.
$oldDesignation = Request::old('designation');
and check it like:
#foreach ($designation as $key => $value)
$selected = '';
#if( $value == $oldDesignation )
$selected = 'selected="selected"';
#endif
<option value="{{ $key }}" {{ $selected }} />{{ $value }}</option>
#endforeach
Reference

Laravel 5 defining old input on select

in my controller, I am passing a list of clients to the view
public function edit(Project $project)
{
$clients = Client::select('clientName', 'id')->get();
return View::make('projects.edit', compact('project', 'clients'));
}
Now in my view, I am currently doing this
<div class="form-group">
{!! Form::label('clientName', 'Client Name:', array('class' => 'col-sm-5 control-label blue')) !!}
<div class="col-sm-7">
<select class="clientName" name="clientName">
#foreach($clients as $client)
#if (Input::old('clients') == $client->id)
<option value="{{ $client->id }}" selected="selected">{{ $client->clientName }}</option>
#else
<option value="{{ $client->id }}">{{ $client->clientName }}</option>
#endif
#endforeach
</select>
</div>
</div>
What I am trying to do is have the default select option set as the old input. At the moment, the select displays with all the clients, but the old value is not default.
How would I go about making it the default option?
Thanks
Update
I do a alternative way I am trying. In my edit function I do
public function edit(Project $project)
{
$clients = Client::lists('clientName', 'id');
return View::make('projects.edit', compact('project', 'clients'));
}
And then in my view I do
<div class="form-group">
{!! Form::label('clientName', 'Client Name:', array('class' => 'col-sm-5 control-label blue')) !!}
<div class="col-sm-7">
{!! Form::select('clientName', $clients, Input::old('clients'), ['class' => 'clientName']) !!}
</div>
</div>
Seem to have the same issue though, the client is not the old client as the default selected option.
Thanks
Your select name is clientName but your old input is looking to a field with the name clients.
The following should work:
<option value="{{ $client->id }}" {!! old('clientName', $project->client->id) == $client->id ? 'selected="selected"' : '' !!}>{{ $client->clientName }}</option>

Categories