delete the previous file with newone on update in laravel - laravel

what happen to my update file?
I can't update file in my program, what's wrong with my controller?
edit.blade.php
<div class="row">
<div class="col-12">
{{ Form::model($activityreports,['route'=>['activityreports.update',$activityreports['id']], 'files'=>true, 'method'=>'GET', 'enctype'=>'multipart/form-data']) }}
<div class="card">
<div class="card-body">
#if(!empty($errors->all()))
<div class="alert alert-danger">
{{ Html::ul($errors->all())}}
</div>
#endif
<div class="row">
<div class="col-md-6">
<div class="form-group">
{{ Form::label('file', 'Laporan Kegiatan') }}
{{ Form::file('file', ['class'=>'form-control']) }}
</div>
</div>
</div>
</div>
</div>
<!-- </form> -->
{{ Form::close() }}
</div>
</div>
controller
public function update(Request $request, $id)
{
//
$rules=[
'title'=>'required',
'date'=>'required',
'type'=>'required',
'place'=>'required'
];
$pesan=[
'title.required'=>'Judul Kegiatan Tidak Boleh Kosong',
'date.required'=>'Tanggal Kegiatan Tidak Boleh Kosong',
'type.required'=>'Jenis Kegiatan Tidak Boleh Kosong',
'place.required'=>'Lokasi Kegiatan Tidak Boleh Kosong',
];
$validator=Validator::make(Input::all(),$rules,$pesan);
if ($validator->fails()) {
return Redirect::to('admin/activityreports/'.$id.'/edit')
->withErrors($validator);
}else{
$fileName="";
$activityreports=Activityreports::find($id);
if($request->hasFile('file')){
Storage::delete($activityreports->file);
$file=$request->file('file');
$fileName=$file->getClientOriginalName();
$file->move('storage/file/activityreportsFile/', $fileName);
$activityreports->file=$fileName;
}
$activityreports->title=Input::get('title');
$activityreports->date=Input::get('date');
$activityreports->type=Input::get('type');
$activityreports->place=Input::get('place');
$activityreports->save();
Session::flash('message','Data Berhasil Diubah');
return Redirect::to('admin/activityreports/index');
}
I tried another code and there is error 'Call to member function getClientOriginalName on null. And when I make file required then input file, there is always warning to input .pdf file.

First, wehre is the problem which causes the error:
This line $file=$request->file('file'); sets $fileto null, therefore you cannot call the function in the next line.
This means that no file is present in your request. You can check your request if you call dd($request->all()) in your update method.
Second, why does this happen?
I think your problem is that you create a GET form in your view and therefore a GET request will be sent. You will probably have to make a POST request (you could also make a PATCH request since you call the update method in your controller).
Please change the form to POST and your route to POST and try it again.

Related

Can't delete first post added by a user in laravel

I am working on social media website with laravel in which posts added by user is listed in user's profile and user can delete the post ,but everything is working perfectly except user can't delete the first post added. Why it is happening. I think the delete function from PostController is not calling when trying to delete first post.
I am giving my code
Route::delete('/deletepost/{id}', 'PostController#delete')->name('deletepost');
PostController.php
public function delete($id)
{
Post::find($id)->delete();
if (Auth::user()->id == 1) {
return redirect(route('admin.dashboard'))
->with('successMsg', 'Place Deleted Successfully');
}else{
return redirect(route('author.dashboard'))
->with('successMsg', 'Place Deleted Successfully');
}
}
code in dashboard.blade.php
#if(Auth::user()->posts)
#foreach(Auth::user()->posts as $post)
<div class="column">
<div class="col-sm-4">
<form id="delete-form-{{$post->id}}" action="{{ route('deletepost',$post->id) }}" method="post" style="display:none">
{{ csrf_field() }}
{{ method_field('delete') }}
</form>
<div class="panel panel-primary">
<button type="button" class="btn btn-link">Edit</button>
<button type="button"
onclick="if(confirm('Are you sure to delete this post?')){
event.preventDefault();
document.getElementById('delete-form-{{$post->id}}').submit();
}else{
event.preventDefault();
}"
class="btn btn-link">Delete</button>
<div class="panel-heading">{{ $post->title }}</div>
<div class="panel-body"><img src="{{ asset('images/'.$post->images->first()->pictures) }}" class="img-responsive" style="width:100%;height:140px" alt="Image"></div>
<div class="panel-footer">{{ $post->category }}</div>
</div>
</div>
</div>
#endforeach
#endif
Note: delete function is working perfectly when deleting posts except first post and i am not getting any errors messages
Try this on PostController
Post::destroy($id);
if(auth()->user()->id() === 1)
return redirect()->route('admin.dashboard')->with('msg', 'deleted!');
return redirect()->route('author.dashboard')->with('msg', 'deleted!');
First line will delete Post based on ID. rest of them are just make it cleaner
UPDATE
Update your form Route
action="{{ route('deletepost',$post->id) }}"
To
action="{{ route('deletepost', ['id' => $post->id]) }}"

Laravel Store function ignored on production server

I'm making a website that 100% works locally but when uploaded to my server everything works except the Store function(/route) for pages.
Expected behaviour when I click the Add button: PageController#store to be executed.
What happens when I click the Add button locally: PageController#store gets executed.
What actually happens when I click the Add button on my server: It just seems to go to pages.index without executing PageController#store.
Let's say I put return "test"; in the Store function instead of the storing logic and change StoreRequest to Request, it still just goes to pages.index without showing the text test even though this also does work locally.
Why is this happening? All the code it the same, and all the other routes and functions work perfectly fine. Everything works except saving/storing.
Routes:
Auth::routes();
Route::get('/', 'HomeController#welcome')->name('welcome');
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('pages', 'PageController');
PageController:
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StorePage;
use App\Http\Requests\UpdatePage;
use App\Page;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
class PageController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$data = [
'pages' => Page::all()
];
return view('pages.index')->with($data);
}
public function create()
{
return view('pages.create');
}
public function store(StorePage $request)
{
$page = new Page();
$page->fill($request->all());
$page->save();
return Redirect::route('pages.index');
}
public function edit(Page $page)
{
$data = [
'page' => $page
];
return view('pages.edit')->with($data);
}
public function update(UpdatePage $request, Page $page)
{
$page->fill($request->all());
$page->save();
return Redirect::route('pages.index');
}
public function destroy(Page $page)
{
$page->delete();
return Redirect::route("pages.index");
}
}
Form:
{{Form::open(array('route' => array('pages.store')))}}
#method('POST')
#csrf
<div class="row">
<div class="col-md-12">
{{ Form::label('title', 'Title:') }}
{{ Form::text('title', null, array('class' => 'form-control '.($errors->has('title') ? ' is-invalid' : ''),'required')) }}
#if ($errors->has('title'))
<small class="text-danger" role="alert">
<strong>{{ $errors->first('title') }}</strong>
</small>
#endif
</div>
</div>
<div class="row">
<div class="col-md-12">
{{ Form::label('identifier', 'Identifier:') }}
{{ Form::text('identifier', null, array('class' => 'form-control '.($errors->has('identifier') ? ' is-invalid' : ''),'required')) }}
#if ($errors->has('identifier'))
<small class="text-danger" role="alert">
<strong>{{ $errors->first('identifier') }}</strong>
</small>
#endif
</div>
</div>
<div class="row">
<div class="col-md-12">
{{ Form::label('content', 'Content:') }}
{{ Form::textarea('content', null, array('class' => 'form-control '.($errors->has('content') ? ' is-invalid' : ''),'required')) }}
#if ($errors->has('content'))
<small class="text-danger" role="alert">
<strong>{{ $errors->first('content') }}</strong>
</small>
#endif
</div>
</div>
<br />
<button type="submit" class="btn btn-primary">Add</button>
{{Form::close()}}
Some files are cached in the server, so you may not be seeing the effect of your application file changes all the time.
Try clearing and reloading your application and route caches by running these commands on the server cli in order:
php artisan cache:clear
php artisan route:cache
php artisan config:cache
composer dump-autoload
After a bit of digging I saw that the request returned 403 Forbidden. I had a folder called 'pages' which is exactly where the POST request was going: /pages/. Renaming this folder fixed my problem.

I can not upload file

i want to import and export a excel file and these are my codes:
This is CustomerController;
public function customersImport(Request $request)
{
if($request->hasFile('customers')) {
$path = $request->file('customers')->getRealPath();
$data = \Excel::load($path)->get();
if ($data->count()) {
dd($value);
foreach ($data as $key => $value) {
$customer_list[] = ['name' => $value->name, 'surname' => $value->surname, 'email' => $value->email];
}
if (!empty($customer_list)) {
Customer::insert($customer_list);
\Session::flash('Success', 'File imported succesfully');
}
}
}
else{
\Session::flash('warning','There is no file to import');
}
return Redirect::back();
}
And this is my customers.blade;
#extends('layouts.app')
#section('content')
<div class="panel-heading">Import and Export Data Into Excel File</div>
<div class="panel-body">
{!!Form::open(array('route'=>'customer.import','method'=>'POST','files'=>'true')) !!}
<div class="row">
<div class="col-xs-10 col-sm-10 col-md-10">
#if(Session::has('success'))
<div class="alert alert-success">
{{Session :: get('message')}}
</div>
#endif
#if(Session::has('warning'))
<div class="alert alert-warning">
{{Session::get('message')}}
</div>
#endif
<div class="form-group">
{!! Form::label('sample_file','Select File to Import:',
['class'=>'col-md-3']) !!}
<div class="col-md-9">
{!! Form::file('customers',array('class'=>'form-control')) !!}
{!! $errors->first('products','<p class="alert alert-danger">:message</p') !!}
</div>
</div>
</div>
<div class="col-xs-2 col-sm-2 col-md-2 text-center">
{!! Form::submit('Upload',['class'=>'btn btn-success']) !!}
</div>
</div>
{!! Form::close() !!}
</div>
#endsection
and when i click upload file error says that:
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
Can you please help me how can i correct that? I dont know what is wrong and error message in the screen is not clear :(
You're POSTing to a GET route. (check here for some more info on different HTTP verbs)
Changing your route to Route::post('customer-import', 'CustomerController#customersImport')->name('customer.import'); should fix this error.

How can I display required message in laravel?

My view like this :
{!! Form::open(['url' => 'product/store','class'=>'form-horizontal') !!}
...
<div class="form-group">
<label for="description" class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
{!! Form::textarea('description', null, ['class' => 'form-control', 'rows'=>5]) !!}
</div>
</div>
...
{!! Form::close() !!}
My controller like this :
use App\Http\Requests\CreateProductRequest;
public function store(CreateProductRequest $request)
{
dd($request->all());
}
My required like this :
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CreateProductRequest extends FormRequest {
public function authorize() {
return true;
}
public function rules() {
return [
'description'=>'required'
];
}
}
If the description is not filled and click submit button, it will not be saved and it will return to the form. When returning to the form, I want to display a message that the description should be filled
I created an html to display a message like this :
<div class="alert alert alert-danger" role="alert">
Description is required
</div>
How can I call the html tag if the description is not filled?
For display a single message I usually use:
#if($errors->has('description'))
<label class="text-danger text-small">{{$errors->first('description')}}</label>
#endif
for more information please check https://laravel.com/docs/5.4/validation#quick-displaying-the-validation-errors
Your all the validation errors are stored in $errors variable. You can access them using $error varibable. But must check if the error message exist using has() method as
#if($errors->has('description'))
<label class="text-danger text-small">{{$errors->first('description')}}</label>
#endif

Laravel Flash errors - How to check if a checkbox is checked?

I'm trying to do flash messages in Laravel, now the flash messages work for success messages and error messages on pages that don't have checkboxes.
I have a view called 'deleteappointmentform' which requires the user to check a checkbox and it deletes the checked appointments, however if I don't check any checkbox and click submit it gives me a success message without actually checking if they've checked and checkboxes. I'm trying to get it to display an error message if they don't check any checkboxes
Any help's appreciated, thanks
This is the function that deals with deleting appointments
function deleteAppointment(Request $request)
{
Appointment::destroy($request->appointments);
Session::flash('successCancelAppointment', 'Appointment cancelled successfully!');
return redirect('all');
}
This is my messages blade
#if (Session::has('successCancelAppointment'))
<div class="alert alert-success" role="alert">
<strong>Success: </strong> {{Session::get('successCancelAppointment')}}
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger" role="alert">
<strong>Errors:</strong>
<ul>
#foreach ($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
This is my deleteappointmentsblade
#extends('layouts.master')
#section('title', 'Cancel Appointment')
#section('content')
<form action="{{url('deleteappointment')}}" method="POST">
{{ csrf_field() }}
#foreach ($appointments as $appointment)
<div>
<label> {{$appointment->user->firstname}} {{$appointment->user->surname}}</label>
<label>Has an appointment at: {{$appointment->time}}</label>
<label>On: {{$appointment->date}}</label>
<label>With Dr: {{$appointment->doctor->surname}}</label>
<input type='checkbox' value='{{$appointment->id}}' name='appointments[]'/>
</div>
#endforeach
<input type="submit" name="submitBtn" value="Cancel Appointments">
</form>
#endsection
you can try this
function deleteAppointment(Request $request)
{ $rules=array(
'appointments'=>'required'
);
$validator = Validator::make($request->all(), $rules);
if($validator->fails())
{
$messages = $validator->messages();
$errors = $messages->all();
return redirect()->back()->withErrors($errors);
}
Appointment::destroy($request->appointments);
Session::flash('successCancelAppointment', 'Appointment cancelled
successfully!');
return redirect('all');
}

Resources