How to fix "Undefined variable: img_name" error in laravel - laravel

i have a project on laravel 5.8; i have this error; please help me :
Undefined variable: img_name
this my html code :
<div class="input-group control-group increment" >
<input id="p_image" type="file" name="p_image" class="form-control">
<div class="input-group-btn">
<button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
</div>
</div>
<div class="clone hide">
<div class="control-group input-group" style="margin-top:10px">
<input id="p_image" type="file" name="p_image" class="form-control">
<div class="input-group-btn">
<button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
</div>
</div>
</div>
My Controller :
public function store(Request $request)
{
$this->validate(request(), [
'p_image' => 'image|mimes:jpg,jpeg,png|max:2048'
]);
if($request->hasFile('p_image')){
$img_name = time() . '.' . $request->p_image->getClientOriginalExtension();
}
// awi sora s lfolder public/uploads
if($request->hasFile('p_image')){
$request->p_image->move(public_path('upload'), $img_name);
}
Image::create([
'p_image' => $img_name,
'post_id' => $post->id
]);
return redirect('/posts');
}
I have this error, i dont understand, if you can explain me please; thank you
Undefined variable: img_name

If $request->hasFile('p_image') is false you don't define the $img_name variable.
But you always execute the code
Image::create([
'p_image' => $img_name,
'post_id' => $post->id
]);
which is wrong. Change your code to
if($request->hasFile('p_image')){
$img_name = time() . '.' . $request->p_image->getClientOriginalExtension();
$request->p_image->move(public_path('upload'), $img_name);
Image::create([
'p_image' => $img_name,
'post_id' => $post->id
]);
}

Related

Upload image file with specified name using laravel

I want to store the image file with the id as a name .
So I tried the following code :
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'casting_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($validator->passes()) {
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_photo' =>$request->casting_photo];
Casting::create($data);
return response()->json(["status" => "success", "message" => "Success! post created."]);
}
return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
}
But it gives me the 500 (Internal Server Error)
EDIT
if ($validator->passes()) {
$input['casting_photo'] = $request->Casting()->id .'.'.$request->casting_photo->extension();
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_name' => $request->casting_name,
'casting_cin' => $request->casting_cin,
'casting_email' => $request->casting_email,
'casting_phone' => $request->casting_phone,
'casting_age' => $request->casting_age,
'casting_sexe' => $request->casting_sexe,
'casting_city' => $request->casting_city,
'casting_address' => $request->casting_address,
'casting_photo'=> $input['casting_photo'] ];
Casting::create($data);
return response()->json(["status" => "success", "message" => "Success! post created."]);
}
return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
I tried that and the same error occurs.
EDIT2
$fileName = $request->get('id') . '.' . $request->file('casting_photo')->extension();
$request->file('casting_photo')->storeAs('castingimages', $fileName);
But in databse I finf the image stored with just the extension like .png
EDIT3
<form id="castingform" method="post" action="castings" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="id" />
<div class="form-group col-md-6">
<label for="casting_name">Nom</label>
<input type="text" class="form-control" id="casting_name" name="casting_name" placeholder="Nom" >
<span class="text-danger">{{ $errors->first('casting_name') }}</span>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Upload</span>
</div>
<div class="custom-file">
<input type="file" name="casting_photo" class="custom-file-input" id="casting_photo">
<div class="input-group-prepend">
<span class="text-danger">{{ $errors->first('casting_photo') }}</span>
</div>
<label class="custom-file-label" for="casting_photo">Choose file</label>
</div>
</div>
<button type="submit" id="createBtn" class="btn btn-success">Sign in</button>
</form>
You are accessing unknown id from request
$input['casting_photo'] = $request->Casting()->id .'.'.$request->casting_photo->extension();
it should be
$request->casting_photo->storeAs(public_path('castingimages'),$request->id.'.'.$request->casting_photo->extension() );
Updated
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_name' => $request->casting_name,
'casting_cin' => $request->casting_cin,
'casting_email' => $request->casting_email,
'casting_phone' => $request->casting_phone,
'casting_age' => $request->casting_age,
'casting_sexe' => $request->casting_sexe,
'casting_city' => $request->casting_city,
'casting_address' => $request->casting_address,
$casting=Casting::create($data);
$casting->casting_photo=$casting->id.'.'.$request->casting_photo->extension() );
$casting->save();

I am trying Laravel Auth but every time I try to login with right credention it return false

The problem is when I try to login it always false, why is this? I am trying auth::attempt() but if always return false. I tried all method but it won't work.
My controller code is:
function checklogin(Request $req)
{
$this->validate($req , [
'email' => 'required|email',
'password' => 'required'
]);
$user_data = array(
'email' => $req->get('email'),
'password' => $req->get('password')
);
//dd($user_data);
if(Auth::attempt($user_data)){
return redirect('admin/successlogin');
}
else{
return back()->with('error' , 'Wrong Login Details');
}
}
my view code
<div class="admin_form">
#if(isset(Auth::user()->email))
<script type="text/javascript">window.location = "/admin/successlogin" </script>
#endif
#if($message = Session::get('error'))
<div class="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert">X</button>
<strong>{{ $message }}</strong>
</div>
#endif
#if(count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="post" action="{{ url('admin/checklogin') }}">
{{ csrf_field() }}
<h2>Admin Login</h2>
<input type="text" name="email" class="text-field" placeholder="Username" />
<input type="text" name="password" class="text-field" placeholder="Password" />
<input type="submit" class="button" value="Log In" />
</form>
</div>
I try every method but it always return false.
try create new user and then Auth::attempt()
User::create(['email' => 'email', 'password' => Hash::make('password')]);
$auth_test = Auth::attempt(['email' => 'email', 'password' => 'password']);
dd($auth_test);

Laravel - How to update checkbox field value

Using Laravel-5.8, I have been able to save the data into the database including the check box field.
protected $fillable = [
'appraisal_name',
'is_current',
'appraisal_start',
'appraisal_end',
];
public function rules()
{
return [
'appraisal_name' => 'required|min:5|max:100',
'appraisal_start' => 'required',
'appraisal_end' => 'required|after_or_equal:appraisal_start',
'is_current' => 'nullable|boolean',
];
}
public function create()
{
return view('appraisal.appraisal_identities.create');
}
public function store(StoreAppraisalIdentityRequest $request)
{
$identity = AppraisalIdentity::create([
'appraisal_name' => $request->appraisal_name,
'appraisal_start' => $appraisalStart,
'appraisal_end' => $appraisalEnd,
'is_current' => $request->has('is_current'),
]);
Session::flash('success', 'Appraisal Initialization is created successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
public function edit($id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$identity = AppraisalIdentity::where('id', $id)->first();
return view('appraisal.appraisal_identities.edit')->with('identity', $identity);
}
public function update(UpdateAppraisalIdentityRequest $request, $id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$appraisalStart = Carbon::parse($request->appraisal_start);
$appraisalEnd = Carbon::parse($request->appraisal_end);
$submissionStart = Carbon::parse($request->submission_start);
$submissionEnd = Carbon::parse($request->submission_end);
$identity = AppraisalIdentity::find($id);
$identity->appraisal_name = $request->appraisal_name;
$identity->appraisal_start = $appraisalStart;
$identity->appraisal_end = $appraisalEnd;
$identity->is_current = $request->has('is_current');
$identity->save();
Session::flash('success', 'Appraisal Initialization is updated successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
create.blade
<form action="{{route('appraisal.appraisal_identities.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3">Is Current Appraisal?</label>
<div class="col-md-9">
<input type="checkbox" class="form-control" name="is_current" value="{{old('is_current')}}">
</div>
</div>
</div>
</div>
</div>
<div>
<!--<input class="btn btn-primary" type="submit" value="{{ trans('global.save') }}">-->
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('appraisal.appraisal_identities.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
edit.blade
<form action="{{route('appraisal.appraisal_identities.update', ['id'=>$identity->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3">Is Current Appraisal?</label>
<div class="col-md-9">
<input type="checkbox" class="form-control" name="is_current" value="{{old('is_current')}}">
</div>
</div>
</div>
</div>
</div>
<div>
<!--<input class="btn btn-primary" type="submit" value="{{ trans('global.save') }}">-->
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('appraisal.appraisal_identities.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
I have these issues while trying to update the data?
The edit checkbox field (is_current) did not pick the value from the database when loaded. It remains unchecked.
is_current is either 0 or 1. The goal is that, there can only be one is_current field that is set to 1 in the table. From the checkbox, when is_current is checked to 1, it should set any other is_current that is 1 to 0 in the table.
How do I resolve these issues?
Thank you.
In edit blade update your checkbox code as this:
<input type="checkbox" class="form-control" name="is_current" #if($identity->is_current == 1) checked #endif value="{{old('is_current')}}">
In your update function change this:
public function update(UpdateAppraisalIdentityRequest $request, $id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$appraisalStart = Carbon::parse($request->appraisal_start);
$appraisalEnd = Carbon::parse($request->appraisal_end);
$submissionStart = Carbon::parse($request->submission_start);
$submissionEnd = Carbon::parse($request->submission_end);
$identity = AppraisalIdentity::find($id);
$identity->appraisal_name = $request->appraisal_name;
$identity->appraisal_start = $appraisalStart;
$identity->appraisal_end = $appraisalEnd;
$identity->is_current = $request->has('is_current');
$identity->save();
// this line update all column to 0 and leave $id field
AppraisalIdentity::where('id', '!=', $id)->update(['is_current' => 0]);
Session::flash('success', 'Appraisal Initialization is updated successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
In your store function change this:
public function store(StoreAppraisalIdentityRequest $request)
{
$identity = AppraisalIdentity::create([
'appraisal_name' => $request->appraisal_name,
'appraisal_start' => $appraisalStart,
'appraisal_end' => $appraisalEnd,
'is_current' => $request->has('is_current'),
]);
$id = $identity->id;
// this line update all column to 0 and leave $id field
AppraisalIdentity::where('id', '!=', $id)->update(['is_current' => 0]);
Session::flash('success', 'Appraisal Initialization is created successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
try this in the edit blade
<
is_current == 1 ? checked : value="{{old('is_current')}}">

Laravel get a empty variable from axios.post from vuie.js module

partners from stackOverflow im making a module using laravel like backend, and vue.js by frontend, i have a form to create a new entity, but the controller dont get the values¡, plz help me to find the error. I'm going to share the code.
the routes.web
//new event from API
Route::resource('/api/events', 'EventsController', ['except' => 'show','create']);
The function in the controller EventsController.php
<?php
namespace soColfecar\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use soColfecar\Http\Requests\CreateEventRequest;
use soColfecar\Http\Requests\UpdateEventRequest;
use soColfecar\User;
use soColfecar\Change;
use soColfecar\Event;
use soColfecar\Event_type;
use Auth;
public function store(Request $request)
{
$exploded = explode(',', $request->banner);
$decoded = base64_decode($exploded[1]);
if(str_contains($exploded[0],'jpeg'))
$extension = 'jpg';
else
$extension = 'png';
$fileName = str_random().'.'.$extension;
$path = public_path().'/storage/banner/'.$fileName;
file_put_contents($path, $decoded);
Event::create([
'event' => strtoupper($request['event']),
'id_event_type' => $request['id_event_type'],
'date_init' => $request['date_init'],
'date_end' => $request['date_end'],
//'banner' => $fileName,
]);
Change::create([
'description' => 'Creo el de evento:'.$request['event'].' correctamente.',
'id_item' => 10,
'id_user' => Auth::user()->id,
]);
return redirect()->route('events.index')
->with('info', 'evento guardado con exito');
}
the method:
<form method="POST" v-on:submit.prevent="storeNewEvent">
<div class="form-group m-form__group">
<label for="eventTypeInput">Tipo de vento:</label>
<v-select :options="eventTypes" v-model="newEvent.id_event_type" id="eventTypeInput">
<template slot="option" slot-scope="option">
{{ option.label }}
</template>
</v-select>
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.city_id }}</span>
</div>
<div class="form-group m-form__group">
<label for="inputHotelName">Nombre del Evento</label>
<input type="text" class="form-control" name="inputHotelName" v-model="newEvent.event" placeholder="Nombre del Evento">
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.hotel_name }}</span>
</div>
<div class="form-group m-form__group">
<label for="date_init_imput">Fecha de inicio</label>
<input class="form-control" type="date" v-model="newEvent.date_init" value="" id="date_init_imput">
</div>
<div class="form-group m-form__group">
<label for="date_end_imput">Fecha de finalizacion</label>
<input class="form-control" type="date" v-model="newEvent.date_end" value="" id="date_end_imput">
</div>
<div class="form-group m-form__group">
<label for="customFile">Banner del Evento</label>
<div></div>
<div class="custom-file">
<input type="file" class="custom-file-input" #change="getLogo" id="customFile">
<label class="custom-file-label" for="customFile">Seleccione archivo</label>
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.logo }}</span>
</div>
</div>
<hr>
<button type="submit" class="btn btn-info waves-effect text-left">Guardar</button>
</form>
data() {
return {
changes: [],
eventTypes: [],
errors: [],
newEvent: {
event: '',
id_event_type: '',
date_init: '',
date_end: '',
banner: '',
}
}
},
storeNewEvent : function() {
var url = 'api/events';
var newEvent = this.newEvent
axios.post(url, {event: this.newEvent}).then(response => {
this.newEvent = {}
this.errors = [];
$('#new_event_modal').modal('hide');
$('.modal-backdrop').remove();
toastr.success('Se ha creado el evento con exito!')
}).catch(error => {
this.errors = error.response.data
});
},
And the error
"Too few arguments to function soColfecar\Http\Controllers\EventsController::store(), 0 passed and exactly 1 expected"
enter image description here
You need to type hint the $request so Laravel knows to fill it in ("dependency injection").
At the top of your file:
use Illuminate\Http\Request;
Then, for your function:
public function store(Request $request) {

Call to a member function getClientOriginalName() on a non-object Laravel

I'm getting this error, and not sure why!
I have the following form:
{{ Form::open( [ 'url' => 'admin/employees/store', 'method' => 'post', 'files' => true, 'class' => 'form-horizontal' ] ) }}
<div class="form-group">
<div class="col-sm-2">Email</div>
<div class="col-lg-3">
<input type="text" name="email" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-sm-2">Files</div>
<div class="col-lg-4">
<input type="file" name="files[]" multiple>
</div>
</div>
<button type="submit" class="btn btn-success btn-sm"><i class="fa fa-check"></i> Save</button>
</form>
Which then just posts to to a controller method:
public function store()
{
$file = Input::file('files');
$name = $file->getClientOriginalName();
$input = Input::all();
print_r($name);
}
Which I just want print out the image that was uploaded for the minute, but the above error keeps showing.
You have a "multi" file upload field - so the file input will be an array
$allFiles = Input::file('files');
foreach ($allFiles as $file)
{
print_r($file->getClientOriginalName());
}

Resources