Editing user info using laravel - laravel

I've built a cms interface for the admin in my website. among other things the admin can add\edit users info using forms.
when I send the edit form I keep getting this error: Column not found: 1054 Unknown column 'updated_at' in 'field list' which suggests that the DB update is trying to save all of the request indexes (which contains values of columns from other table) and not just the one I'm trying to update.
I've manage to track the problem to one line $user_role->save();.
the lines above that do what their suppose to (finding thr correcct user_role and change its value).
Here is my code
Model
static public function update_user($request, $id){
$image_name = '';
if( !empty($request['profile_image']) && $request->hasFile('profile_image') && $request->file('profile_image')->isValid() ){
$file = $request->file('profile_image');
$image_name = date('Y.m.d.H.i.s') . '-' . $file->getClientOriginalName();
$request->file('profile_image')->move( public_path() . '/images/profile-images/' , $image_name);
$img = Image::make( public_path() . '/images/profile-images/' . $image_name );
$img->resize(370, null, function ($constraint) {
$constraint->aspectRatio();
});
$img->save();
}
$user = self::find($id);
$user->name = $request['name'];
$user->email = $request['email'];
$user->phone = $request['phone'];
if( !empty($request['password']) ){
$user->password = bcrypt($request['password']);
}
if(!empty($image_name)){
$user->profile_image = $image_name;
}
if( !empty($request['role_id']) ){
$user_role = Users_role::find($id);
$user_role->role_id = $request['role_id'];
$user_role->save();
}
$user->save();
Session::flash('sm', 'Your profile has been updated');
Session::flash('sm-position', 'toast-top-center');
Session::put('user_name', $request['name']);
}
View
<div class="row">
<div class="span9">
<div class="content">
<div class="module message">
<div class="module-head">
<h3><b>Edit Product</b></h3>
</div><br>
<div class="content">
<div class="module message">
<div class="module-body">
<form action="{{ url('cms/users/' . $user->id) }}" method="POST" novalidate="novalidate" autocomplete="off" enctype="multipart/form-data">
<div class="module-body">
#method('PUT')
#csrf
<input type="hidden" name="user_id" value="{{ $user->id}}">
<div class="form-group">
<div class="input-group mb-3">
<div class="w-100 field-input-cms">
<label for="category-id" class="input-group-text h-50"><span class="text-danger">*</span><b> Permissions:</b></label>
<select name="role_id" class="custom-select span-8">
<option #if ( $user->role_id == 8 ) selected="selected" #endif value="8">Admin</option>
<option #if ( $user->role_id == 2 ) selected="selected" #endif value="2">Regular</option>
</select>
</div>
<small class="text-muted help-text">Please select one option</small><br>
<span class="text-danger"> {{ $errors->first('category_id') }}</span>
</div>
<div class="w-100 field-input-cms">
<label for="name" class="input-group-text h-100"><span class="text-danger">*</span><b> Name:</b></label>
<input type="text" value="{{ $user->name }}" name="name" style="width:100%" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default">
</div>
<small class="text-muted help-text">Name of user</small><br>
<span class="text-danger"> {{ $errors->first('name') }}</span>
<div class="field-input-cms w-100">
<label for="email" class="input-group-text"><span class="text-danger">*</span><b> Email:</b></label>
<input type="text" value="{{ $user->email }}" name="email" size="120" class="form-control mw-100" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default">
</div>
<small class="text-muted text-balck help-text"> Email of user</small><br>
<span class="text-danger"> {{ $errors->first('email') }}</span>
<div class="field-input-cms w-100">
<label for="phone" class="input-group-text"><span class="text-danger">*</span><b> Phone:</b></label>
<input type="text" value="{{ $user->phone }}" name="phone" size="120" class="form-control mw-100" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default">
</div>
<small class="text-muted text-balck help-text"> Phone number of user</small><br>
<span class="text-danger"> {{ $errors->first('phone') }}</span>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
</div>
<div class="custom-file">
<input type="file" name="profile_image" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" name="profile_image" for="inputGroupFile01">Choose file</label>
</div>
</div>
<small class="text-muted help-text">Image must be: jpg, jpeg, png, gif. Max: 5mb</small><br>
<span class="text-danger"> {{ $errors->first('profile_image') }}</span>
</div>
<div class="form-group">
<img id="cms-profile-image" src="{{ asset('images/' . $user->profile_image) }}" >
</div><br>
<a class="btn btn-inverse" href="{{ url('cms/users') }}">Cancel</a>
<input type="submit" value="Save Product" name="submit" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
</div>
</div> <!--/.content-->
</div><!--/.span9-->
</div>
Image of the error gaven by laravel
I should mention that if I comment out this code:
if( !empty($request['role_id']) ){
$user_role = Users_role::find($id);
$user_role->role_id = $request['role_id'];
$user_role->update();
}
all the values are saved correctly.

If your users table doesn't have created_at and updated_at columns you should set:
public $timestamps = false;
in your User model.
Laravel by default assumes you have those fields for tables. So whenever record is created/updated it will automatically set/update those fields.
Alternatively you can update your table structure to add those fields and then those fields will be automatically handled by Laravel (in such case don't set timestamps to false).
You might be interested to read about Eloquent conventions

Related

Laravel : Call to a member function getClientOriginalName() on null when Update Data

I will update the data its contain image, then when I will send to update here's the error Call to a member function getClientOriginalName()
This is my Controller
public function updateBook(Request $request, $id){
$book = DB::table('books')->where('id',$id);
$old = $book->select('images');
$ChecK = 0;
$file = var_dump($request->file('images')->getClientOriginalName());
$filename = time().$file;
$path = public_path('/Uploads');
if($request->hasFile('images')){
$file = $request->file('images');
$file->move($path, $filename);
Storage::delete($old);
$ChecK = 1;
}
else {
dd('Request Hash No File!');
}
$data = [
'name'=> $request->input('bookName'),
'year'=> $request->input('tahunT'),
'author'=> $request->input('author'),
'summary'=> $request->input('Summary'),
'publisher'=> $request->input('publishers'),
'pageCount' => $request->input('pageCount'),
'readPage'=> $request->input('ReadPage'),
'finished' => '$pageCount' == '$readPage' ? true : false,
'reading' => '$readPage' > 0 ? true : false,
'updatedAt'=> new DateTime()
];
if( $ChecK == 1){
$data = ['images' => $filename];
$book->update($data);
return redirect('home')->with('status', 'update succesfully');
}
else {
$data = ['images' => $old];
$book->update($data);
return redirect('home')->with('status', 'Update with old image ');
}
}
Here is the view
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
#foreach ($toEdit as $dt)
<form class="row g-3" enctype="multipart/form-data" method="POST" action="{{ route('update', $dt->id) }}" value="PUT">
{{ csrf_field() }}
<div class="col-md-6">
<label for="bookName" class="form-label">Nama Buku:</label>
<input type="text" class="form-control" name ="bookName"id="bookName" value="{{ ($dt->name) }}">
</div>
<div class="col-md-3">
<label for="tahunT" class="form-label">Tahun Terbit : </label>
<input type="number" class="form-control" name="tahunT" id="tahunT" value="{{ ($dt->year) }}">
</div>
<div class="col-md-3">
<label for="author" class="form-label">Author : </label>
<input type="text" class="form-control" name="author" id="author" value="{{ ($dt->author) }}">
</div>
<div class="col-md-6">
<label for="publishers" class="form-label">Publisher : </label>
<input type="text" class="form-control" name="publishers" id="publishers" value="{{ ($dt->publisher) }}">
</div>
<div class="col-md-3">
<label for="pageCount" class="form-label">Page Count :</label>
<input type="number" class="form-control" name="pageCount" id="pageCount" value="{{ ($dt->pageCount) }}">
</div>
<div class="col-md-3">
<label for="ReadPage" class="form-label">Read Page :</label>
<input type="number" class="form-control" name="ReadPage" id="ReadPage"value="{{ ($dt->readPage) }}">
</div>
<div class="col-12">
<label for="Summary" class="form-label">Summary :</label>
<textarea class="form-control" name="Summary" id="Summary">{{ ($dt->summary) }}</textarea>
</div>
<div class="col-md-12">
<label for="images" class="form-label">Book Image :</label>
<input type="file" class="form-group" name="images">
<br>
<img src="{{ asset('Uploads/'.$dt->images) }}" widht="300px"/>
<br>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
#endforeach
</div>
Here, I will update the data, if user want to change the images, so the image will be update and if no, the images use the old one. It's rull same as the other input. But, when I try to upload the new one, the error Call to a member function getClientOriginalName() happen.
Do you have any suggestion to this? I already add the code enctype="multipart/form-data" and var_dump() but the error was same. Thank you :)
You have to check, with a condition, if your image is null or not in order to avoid this error.
Try something like :
if ( isset($request->file('images')) != null ) {
$ChecK = 0;
$file = $request->file('images')->getClientOriginalName();
$filename = time().$file;
$path = public_path('/Uploads');
}
//..
Just add a simple condition :
If($request->file('image')) {
...
$request->images->getClientOriginalNe();
.....
}

how to display pdf in embed tag after click button?

I have a form with a filter and a submit button. I would like to display a pdf in an embed tag on the same page with the filter fields used when generating the pdf with Dompdf. Thanks in advance.
here is the form :
#section('content')
<!-- Your html goes here -->
<div class='panel panel-default'>
<div class='panel-heading'>Customer Statement</div>
<div class='panel-body'>
<form method='get' action="{{ route('getStatement') }}" id="statementForm">
#csrf
<div class="row">
<div class='col-sm-6 form-group'>
<div class="form-group col-6">
<label for="start_date"><strong>Start Date</strong></label>
<input type="date" required name="start_date" value="{{ date('Y-m-d') }}"
class="form-control" id="start_date">
</div>
</div>
<div class='col-sm-6 form-group'>
<div class="form-group col-6">
<label for="end_date"><strong>End Date</strong></label>
<input type="date" required name="end_date" value="{{ date('Y-m-d') }}"
class="form-control" id="end_date">
</div>
</div>
</div>
<div class='col-sm-12 form-group'>
<label> Customers :</label>
<select style="font-size: 12px; width:100%" id="customer_id" name="customer_id"
class="select2 mb-2 select2-multiple">
<option value=''> Choose </option>
#if ($customers)
#foreach ($customers as $item)
#php $selected = ''; #endphp
#if (isset($customerdirect) == $item->id)
#php $selected = 'selected'; #endphp
#endif
<option data-name="{{ $item->name }}" value='{{ $item->id }}' {{ $selected }}>
{{ $item->name }} </option>
#endforeach
#endif
</select>
</div>
</div>
<div class='panel-footer'>
<input type='submit' class='btn btn-success' value='Generate'/>
</div>
</form>
</div>
#endsection
the code in controller
public function getStatement(Request $request)
{
$pdf = PDF::loadView('customerslocations::customerstatementpdf');
return $pdf->stream();
}

Laravel : save radio group with difference key

I want to save radios group in database with different question_id
I tried to use form with radio's input have name=answer
controller :
public function store(Request $request, Survey $survey)
{
$question = \App\Question::where('survey_id', '=' , $survey->id)->get();
$request->validate([
'answer'=>'required'
]);
$arr = $request->except('_token');
$newAnswer = new Answer();
$newAnswer->answer = request()->get('answer');
foreach ($survey->questions as $key=>$question){
$newAnswer->question_id = $question->id;
}
$newAnswer->user_id = Auth::id();
$newAnswer->last_ip = request()->ip();
$newAnswer->survey_id = $survey->id;
$newAnswer->commentaire = request()->get('commentaire');
givePoint(new VoteAdded($newAnswer));
$newAnswer->save();
return redirect()->action('SurveyController#view_survey_answers', [$survey->id]);
}
view :
<div id="Create" class="col-12" style="display:none;">
{!! Form::open(array('action'=>array('AnswerController#store', $survey->id))) !!}
<div class="text-center">
<img class="rounded"
src="https://interactive-examples.mdn.mozilla.net/media/examples/grapefruit-slice-332-332.jpg"
alt="Grapefruit slice atop a pile of other slices" />
</div>
<hr>
#foreach ($survey->questions as $question)
<p class="flow-text">Question {{ $zero++}} - {{ $question->title }}</p>
#if($question->question_type === 'text')
<div class="form-group" style="margin-left: 20px;">
<div class="input-field col s12">
<input id="answer" type="text" name="answer">
<label for="answer">Answer</label>
</div>
</div>
#elseif($question->question_type === 'textarea')
<div class="form-group" style="margin-left: 20px;">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea" name="{{ $question->id }}[answer]"></textarea>
<label for="textarea1">Textarea</label>
</div>
</div>
#elseif($question->question_type === 'radio')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
#if($value === 'else')
<div class="form-group" style="margin-left: 20px;">
<input name="answer" class="custom-control-input" type="radio" id="{{ $value }}" value="{{$value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
<div id="textboxes" style="display: none">
<br>
<textarea class="form-control" name="commentaire" id="exampleFormControlTextarea1" rows="3" placeholder="Write a large text here ..."></textarea>
</div>
</div>
#else
<p style="margin:0px; padding:0px;">
<div class="form-group" style="margin-left: 20px;">
<input name="answer[{{$question->id}}]" class="custom-control-input" type="radio" id="{{ $value }}" value="{{ $value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
</div>
</p>
#endif
#endforeach
#elseif($question->question_type === 'checkbox')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<div class="form-group">
<input type="checkbox" id="{{ $value }}" name="answer" value="{{$value}}"/>
<label for="{{$value}}">{{ $value }}</label>
</div>
</p>
#endforeach
#endif
<div class="divider" style="margin:10px 10px;"></div>
#endforeach
<div class="form-group">
{{ Form::submit('Submit Survey', array('class'=>'btn btn-success mt-4')) }}
</div>
{!! Form::close() !!}
</div>
Tables :
i have already made it :
Answer table = id, survey_id , question_id , answer . commentaire ,
timestamp
Survey table : id title ...
question table : id , suvey_id , option_type , options
I got in my database a array: ["question_id" = "value"]
what a want is for example i have 2 questions , in my database i want to save 2 row with some survey id but different question id
could you help me to do that ?
-Since 1 survey can have many questions create a separate table for questions like survey_questions
-You can insert in multiple tables at the same time by writing insert queries for the survey and survey questions table separately and wrapping it in a transaction. In Laravel, you can do something like
try{
DB::transaction();
//insert in survey table
//insert in survey questions table
DB::commit();
} catch(\Exception $e){
DB::rollback()
}

Error About Laravel Blade Foreach in Loop if else

There are problem my code about foreach and if condition. When I pulled else code block out of foreach loop there are no problem it is work. But I put in else code in loop. Else dont work and dont show anything.
My purpose, programme check to used user_id in total_bonuses datatable if ok I want to display only update form if no records user_id in total_bonuses I want to show store forum and user add to info. It seems to complicated.
My controller code is below
public function show($lang=null, $id)
{
$bonuses = DB::table('reservations')
->select(DB::raw('SUM(bonus) as total_bonus, user_id'))
->where('user_id', '=', $id)
->groupBy('user_id')
->get();
$dolars = DB::table('reservations')
->select(DB::raw('SUM(dolar) as dolar, user_id'))
->where('user_id', '=', $id)
->groupBy('user_id')
->get();
$confirmeds = DB::table('reservations')
->select(DB::raw('SUM(confirmation) as confirmed, user_id'))
->where('confirmation', '=', 1)
->where('user_id', '=', $id)
->groupBy('user_id')
->get();
$user = DB::table('users')->find($id);
$totals = DB::table('total_bonuses')->where('user_id', '=', $id)->get();
return view('wallet.show', compact('totals', 'user', 'bonuses', 'dolars', 'confirmeds'));
}
View Code is below
#foreach ($totals as $total)
#if ($total->new_dollar !== NULL)
<div class="col-12"><a href="javascript:void(0)" class="link"><i class="mdi mdi-check-circle text-success"></i> <font class="font-medium"> {!! $total->new_dollar !!}
Remaining Dollar</font></a></div>
#endif
</div>
</center>
</div>
<div>
</div>
</div>
</div>
<!-- Column -->
<!-- Column -->
<div class="col-lg-8 col-xlg-9 col-md-7">
<div class="card">
#if (count($total->user_id) === 1)
<br>
<br>
<label class="col-md-12"><h4> Paid Dollar</h4></label>
<form class="form-horizontal form-material" method="POST" action="{{ route ('total.update', ['lang' => App::getLocale(), 'id' => $total->id]) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PATCH">
<input type="hidden" name='id' value='{!! $total->id !!}'>
<input type="hidden" name='user_id' value='{!! $user->id !!}'>
<div class="form-group">
<label class="col-md-12">Total Dollar</label>
<div class="col-md-12">
<input name="old_dollar" type="text" value="{!! $total->new_dollar !!}" class="form-control form-control-line" readonly>
</div>
</div>
<div class="form-group">
<label class="col-md-12">Paid Dollar</label>
<div class="col-md-12">
<input name="paid_dollar" type="text" class="form-control form-control-line">
</div>
</div>
<div class="form-group">
<label class="col-md-12">Note (Optionally! Not Required)</label>
<div class="col-md-12">
<input name="bonus_note" type="text" class="form-control form-control-line">
</div>
</div>
<input name="moderator_id" type="hidden" value="{{ Auth::user()->id }}">
<div class="form-group">
<div class="col-sm-12">
<button class="btn btn-success" type="submit">{{ __('profile.update')}}</button>
</div>
</div>
</form>
#else
<form class="form-horizontal form-material" method="POST" action="{{ route ('total.store', ['lang' => App::getLocale()]) }}">
{{ csrf_field() }}
<input type="hidden" name='user_id' value='{!! $user->id !!}'>
<div class="form-group">
<label class="col-md-12">Total Dollar</label>
<div class="col-md-12">
<input name="old_dollar" type="text" value="#foreach ($dolars as $dolar)
{{ $dolar->dolar }}
#endforeach" class="form-control form-control-line" readonly>
</div>
</div>
<div class="form-group">
<label class="col-md-12">Paid Dollar</label>
<div class="col-md-12">
<input name="paid_dollar" type="text" class="form-control form-control-line">
</div>
</div>
<div class="form-group">
<label class="col-md-12">Note (Optionally! Not Required)</label>
<div class="col-md-12">
<input name="bonus_note" type="text" class="form-control form-control-line">
</div>
</div>
<input name="moderator_id" type="hidden" value="{{ Auth::user()->id }}">
<div class="form-group">
<div class="col-sm-12">
<button class="btn btn-success" type="submit">{{ __('profile.update')}}</button>
</div>
</div>
</form>
#endif
#endforeach
Best wishes.
The problem in your provided view is with the if condition. Here you are trying to count the user id which is not possible:-
#if (count($total->user_id) === 1)
Change the above code to
#if (count($total) === 1)

Hidden type input value not being passed in Laravel gallery Project

I have created an album. I am trying to upload photos to the album and storing the album_id through the 'hidden' type input. When i check the source code, album_id is shown in 'value' attribute but unfortunately the value is not being passed to the query during form submission.
My create method of PhotoController which shows the form
public function create($id)
{
$albums = Album::where('id',$id)->first();
return view('admin.pages.photos',compact('albums', 'id'));
}
Here is the form.
<div class="container">
<div class="row">
<a class="btn btn-success" href="/gallery/{{$albums->slug}}">Back to Gallery</a>
<h4>Upload Photos to <strong>{{$albums-> name}}</strong> Gallery</h4>
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
<img class="thumbnail" src="/images/gallery/{{$albums->cover_pic}}" alt="{{$albums->name}}">
</div>
<div class="col-md-8">
<form class="form-horizontal" action="/photo" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-8">Photo Title:</label>
<input type="text" name="photo_name" class="form-control" placeholder="Name of the Photo" value="{{ old('photo_name') }}" >
</div>
<div class="form-group">
<label class="col-md-8">Description</label>
<input type="text" name="desc" class="form-control" placeholder="Write Description" value="{{ old('desc') }}">
</div>
<div class="form-group">
<label class="col-md-8">Upload Pic</label>
<input type="file" name="photo" class="form-control" value="{{old('photo')}}" >
</div>
<input type="hidden" name="album_id" value="{{$albums->id}}">
<button type="submit" name="submit" class="btn btn-success waves-effect waves-light m-r-10">Submit</button>
</form>
and the store method
public function store(Request $request)
{
$this->validate($request, [
'photo_name'=>'required|min:3',
'desc'=>'required',
'photo'=>'required'
]);
$photo = new Photo;
$photo->album_id = $request->album_id;
$photo->photo_name = $request->photo_name;
$str = strtolower($request->photo_name);
$photo->slug = preg_replace('/\s+/', '-', $str);
if($file=$request->file('photo')){
$name = time().'.'.$file->getClientOriginalName();
$file->move('images/gallery', $name);
$photo['photo'] = $name;
}
$photo->desc = $request->desc;
$photo->save();
return redirect()->back()->with('status', 'Photo Successfully Added!');
}

Resources