How I upload an image on laravel 6? - php

im trying to edit an image on laravel 6, but but it does not advance to next view, stays on the form view.
I have seen many tutorials of laravel 5.8 and 6. I can't make it work in any way
This is de controller:
public function update(Request $request, $id)
{
$validator = $request->validate([
'titulo' => 'required | max:50', //campo obligatorio y máximo 50 caracteres
'contenido' => 'required | max:150',
'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
]);
$image_name = time().'.'.$request->imagen->getClientOriginalExtension();
$request->image->move(public_path('images'), $image_name);
$datos = array(
'titulo' => $request->titulo,
'contenido' => $request->contenido,
'imagen' => $image_name,
);
Noticia::whereId($id)->update($datos);
return redirect('/mostrar');
}
THis is Web.php file:
Route::get('/actualizar/{id}', 'crearNoticiaController#update')->name('actualizar');
Route::get('/editar/{id}', 'crearNoticiaController#edit')->name('editar');
this is form file:
<div class="subir-imagen">
<form method="get" action="{{ route('actualizar', $noticia->id) }}" enctype="multipart/form-data">
#csrf
<div class="crear-titulo">
<input class="titulo" type="text" name="titulo" placeholder="Escriba el titulo" value="{{$noticia->titulo}}">
</div>
<div class="crear-contenido">
<textarea class="ckeditor" name="contenido" placeholder="Escriba el contenido" >
{{$noticia->contenido}}
</textarea>
</div>
<table border="2">
<tr>
<td><img src="{{URL::to('/')}}/images/{{$noticia->imagen}}" alt="imagen" width="250" align="left"/></td>
</tr>
</table>
<div class="form-group">
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" />
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<input type="submit" class="btn btn-primary" value="Enviar" id="btn-enviar" />
</div>
</div>
</form>
</div>
Thnaks for help

I faced same issue, but luckily i solved this problem.I added my solution below, i think this will help you to solve this problem
public function updatePost(Request $request, $id)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:25|min:4',
'image' => 'mimes:jpeg,jpg,png,JPEG,JPG,PNG | max:100000',
]);
$data = array();
$data['category_id'] = $request->category_id;
$data['title'] = $request->title;
$data['details'] = $request->details;
$image = $request->file('image');
if($image)
{
$image_name = hexdec(uniqid());
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$upload_path = 'public/assets/img/';
$image_url = $upload_path.$image_full_name;
$success = $image->move($upload_path,$image_full_name);
$data['image'] = $image_url;
unlink($request->old_photo);
$posts = DB::table('posts')->where('posts.id', $id)->update($data);
if($posts)
{
return Redirect()->route('all.posts')->with('success','Posts are inserted successfully');
}
else
{
return back()->with('error', 'Posts are not inserted successfully');
}
}
else
{
$data['image'] = $request->old_photo;
$posts = DB::table('posts')->where('posts.id', $id)->update($data);
if($posts)
{
return Redirect()->route('all.posts')->with('success','Posts are inserted successfully');
}
else
{
return back()->with('error', 'Posts are not inserted successfully');
}
}
}
edit_post.blade.php
#extends('welcome')
#section('content')
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<p>
List Posts
</p>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ url('posts.update_posts/'.$posts->id) }}" method="post" enctype="multipart/form-data">
#csrf
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<div>Category Name</div>
<label>Category ID</label>
<select class="form-control" name="category_id">
#foreach($category as $categories)
<option value="{{ $categories->id }}" <?php if ($categories->id == $posts->category_id)
echo "selected"; ?> > {{ $categories->name }} </option>
#endforeach
</select>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Product Title</label>
<input type="text" name="title" class="form-control" value="{{ $posts->title }}" id="title" required data-validation-required-message="Please product name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Details</label>
<textarea name="details" rows="5" class="form-control" value="{{ $posts->details }}" id="details"></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Product Image</label>
<input type="file" name="image" class="form-control" id="image"><br/>
Old Image : <img src="{{ URL::to($posts->image) }}" style="hight: 40px; width: 100px">
<input type="hidden" name="old_photo" value="{{ $posts->image }}">
</div>
</div>
<br>
<div id="success"></div>
<div class="form-group">
<button type="submit" class="btn btn-success" id="sendMessageButton">Update</button>
</div>
</form>
</div>
</div>
</div>
#endsection

First run on your project console command:
php artisan storage:link
Then try this code and if return any error message tell me khow:
$imagen = $request->file("imagen");
$extension = $imagen->extension();
$filename = time().".".$extension;
$request->file('imagen')->storeAs("public/images", $filename);
Finally check your public/images folder for image file exists.
Also you can read about storing uploaded files in laravel 6.x official documentation

I've solved with this way:
In web.php I put patch instead get
Route::patch('/actualizar/{id}', 'crearNoticiaController#update')->name('actualizar');
In the edit blade I put: #method('PATCH')
And this is the update in the controller:
public function update(Request $request, $id)
{
$noticia = Noticia::findOrFail($id);
$noticia->titulo = $request->get('titulo');
$noticia->contenido = $request->get('contenido');
$noticia->imagen = $request->file('imagen');
$validator = $request->validate([
'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
]);
$imageName = time().'.'.request()->imagen->getClientOriginalExtension();
request()->imagen->move(public_path('images'), $imageName);
$noticia->imagen = $imageName;
$noticia->update();
return redirect('/mostrar'); //Redirigimos a la la vista para mostrar las noticias
}

Related

Laravel: I can't upload my dropzone file into my database

Hi I am new to laravel and javascript,
I have a multiple input forms for updating of product information including a image upload using Dropzone.js to update product image. However I cant see to update my image file as I keep getting a null value for my dropzone image when I have already dragged a file in.
Below are my codes in the product-edit page:
<form action="{{ route('merchant.product.update', $product->prodID) }}" method="POST" class="dropzone" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<div class="form-group">
<h5>Code</h5>
<input type="text" name="prodCode" class="form-control" id="prodCode" placeholder="Product Code" value="{{ old('prodCode', $product->prodCode) }}" required>
<div class="spacer"></div>
</div>
<div class="form-group">
<h5>Description</h5>
<textarea id="prodDesc" name="prodDesc" class="form-control" id="prodDesc" placeholder="Description" rows="5" required> {{ $product->prodDesc }}</textarea>
<div class="spacer"></div>
</div>
<div class="form-group">
<h5>Price</h5>
<input type="text" name="price" class="form-control" id="price" placeholder="Price" value="{{ old('price', $product->price)}}">
<div class="spacer"></div>
</div>
<div class="form-group">
<h5>Quantity</h5>
<input type="number" name="quantity" class="form-control" id="quantity" placeholder="Quantity" value="{{ old('quantity', $product->quantity)}}">
<div class="spacer"></div>
</div>
<div class="form-group">
<h5>Feature Product</h5>
<div class="switch">
<input type="checkbox" name="featured" class="switch-input" value="1" {{ old('featured', $product->featured=="true") ? 'checked="checked"' : '' }}/>
<div class="circle"></div>
</div>
</div>
<div class="form-group">
<h5>Product Image</h5>
<div id="dropzoneDragArea" class="dz-default dz-message dropzoneDragArea">
<span>Upload Image</span>
</div>
<div class="dropzone-previews"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-large btn-primary">Update Product</button>
</div>
<div class="spacer"></div>
</form>
Below are the Javascript portion of the blade.php:
Below are my Controller Methods I have for the update:
public function storeImage(Request $request) {
if($request->file('file')){
// Upload path
$destinationPath = 'img/products/';
// Get File
$image = $request->file('file');
// Get File Name
$imageName = $image->getClientOriginalName();
// Uploading File to given path
$image->move($destinationPath,$imageName);
$product = new Product();
$product->where('prodID', '=', $request->{'prodID'}, 'AND', 'created_by_merchant_id', '=', $this->checkMerchantID())
->update([
'prodImage' => $imageName,
]);
}
}
//update Product details
public function update(Request $request, $prodID)
{
if ($this->isCodeExist($request->{'prodCode'}, $request->{'prodID'})) {
return back()->withErrors('This code already exists!');
}
try{
$db = new Product();
$db->where('prodID', '=', $prodID, 'AND', 'created_by_merchant_id', '=', $this->checkMerchantID())
->update([
'prodCode' => $request->{'prodCode'},
'prodImage' =>$this->storeImage($request),
'prodDesc' => $request->{'prodDesc'},
'price' => $request->{'price'},
'quantity' => $request->{'quantity'},
'featured' => $request->input('featured') ? true : false,
]);
return back()->with('success_message', 'Product updated successfully!');
} catch (\Illuminate\Database\QueryException $ex) {
Log::channel('merchant_error')->error($ex);
return back()->withErrors('There seems to be an error in updating');
}
}

LARAVEL 6.x = Trying to get property 'id' of non-object

I wish to be able to edit my users through the admin panel but this returns the following error to me:
Trying to get property 'id' of non-object
it will be an error in my view with the call of the variable ID if I change it I have the same thing with my variable name.
I use the users table and in no other place in my code do I have problems
help me please
URI : /role-edit/{id}
View :
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4>Edit register roles</h4>
</div>
<div class="card-body">
<form action="/role-register-update/{{ $users->id }}" method="POST">
{{ csrf_field() }}
{{ method_field('PUT') }}
<div class="form-group">
<label>Name</label>
<input type="text" name="name" value="{{ $users->name }}" class="form-control">
</div>
<div class="form-group">
<label>Give role</label>
<select name="type" class="form-control">
<option value="admin">Admin</option>
<option value="vendor">Vendor</option>
<option value="">None</option>
</select>
<button type="submit" class="btn btn-success">Update</button>
Cancel
</div>
</form>
</div>
</div>
</div>
</div>
</div>
Controller :
class DashboardController extends Controller
{
public function registered()
{
$users = User::all();
return view('admin.registeradmin')->with('users', $users);
}
public function edit(Request $request,$id)
{
$users = User::findOrFail($id);
return view('admin.edit-register')->with('users',$users);
}
public function update(Request $request, $id)
{
$users = User::findOrFail($id);
$users->name = $request->input('name');
$users->usertype = $request->input('type');
$users->update();
return redirect('/role-register')->with('status', 'You data is update');
}
public function destroy($id)
{
$users = User::where('id', $id);
if ($users != null)
{
$users->delete();
return redirect('/role-register')->with('status', 'User is correctly deleted !');
}
return redirect('/role-register')->with('status', 'User is not correctly deleted !');
}
}
Routes :
Route::get('/', function () {
return view('pages.home');
});
Route::get('/aboutus', function () {
return view('pages.aboutus');
})->name('aboutus');
Auth::routes();
Route::get('profile', 'UserProfileController#show')->middleware('auth')->name('profile.show');
Route::post('profile', 'UserProfileController#update')->middleware('auth')->name('profile.update');
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['middleware' => ['auth', 'admin']], function () {
Route::get('/dashboard', function () {
return view('admin.dashboard');
});
Route::get('/role-register', 'Admin\DashboardController#registered');
Route::get('/role-edit/{id}', 'Admin\DashboardController#edit');
Route::put('/role-register-update/{id}', 'Admin\DashboardController#update');
Route::delete('/role-delete/{id}', 'Admin\DashboardController#destroy');
});
Add dd($users) in the edit function of your controller. If you get the data, add the following to the form action form action:
{{route('routename',['id'=>$users->id])}}
// Controller
public function Updateprofile(Request $request)
{
if (Auth::check() && Auth::user()->role->id == 2) {
$this->validate($request, [
'name' => 'required',
'email' => 'required|email'
]);
$image = $request->file('image');
$slug = str_slug($request->name);
if (isset($image))
{
$currentDate = Carbon::now()->toDateString();
$imagename = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(600,500);
if (!file_exists('storage/uploads/profile'))
{
mkdir('storage/uploads/profile',0777,true);
}
unlink('storage/uploads/profile/'.Auth::user()->image);
$image_resize->save('storage/uploads/profile/'.$imagename);
}else{
$imagename = Auth::user()->image;
}
$user = User::find(Auth::id());
$user->name = $request->name;
$user->email = $request->email;
$user->image = $imagename;
$user->save();
Toastr::success('Profile Successfully Updated :)', 'Success');
return redirect()->back();
}
}
// blade file
<form method="POST" action="{{route('user.profile.update')}}" class="form-horizontal" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="row clearfix">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
<label for="name">Name : </label>
</div>
<div class="col-lg-10 col-md-10 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
<input type="text" id="name" class="form-control" placeholder="Enter your name" name="name" value="{{Auth::user()->name}} {{old('name')}}">
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
<label for="image">{{__('Image')}} : </label>
</div>
<div class="col-lg-10 col-md-10 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
<input type="file" name="image" >
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
<label for="email_address_2">Email Address</label>
</div>
<div class="col-lg-10 col-md-10 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
<input type="text" id="email_address_2" class="form-control" value="{{Auth::user()->email}} {{old('email')}}" placeholder="Enter your email address" name="email" ">
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-offset-2 col-md-offset-2 col-sm-offset-4 col-xs-offset-5">
<button type="submit" class="btn btn-primary m-t-15 waves-effect">UPDATE</button>
</div>
</div>
</form>

Laravel 5.5 Crud Routing

I am new to Laravel 5.5 and I am trying to create a CRUD. Right now I am experiencing a views error. I am not sure where I went wrong. If someone point me in the right direction it would be greatly appreciated.
I have tried a few different attempts at resolving this issue such as changing my routes to Uppercase L instead of lower case l for leads to have it follow the directory casing but no avail.
My error
Route [leads.create] not defined. (View: .../resources/views/leads/index.blade.php)
Error's source coming from my index.blade.php file
<div class="pull-right">
<div class="btn-group"> <a href="{{ route('leads.create') }}" class="btn btn-info" >Add New</a> </div>
</div>
My Tree
views
|-- leads
| |-- create.blade.php
| |-- edit.blade.php
| |-- index.blade.php
| `-- show.blade.php
My Web.php
// Leads
Route::resource('Leads','LeadsController');
Route::get('leads/index', function () { return view('Leads.index'); });
Route::get('leads/create', function () { return view('Leads.create'); });
My Controller
namespace App\Http\Controllers;
use App\Leads;
use Illuminate\Http\Request;
class LeadsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$videos = Leads::orderBy('id','DESC')->paginate(5);
return view('leads.index',compact('leads'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('leads.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'first_name' => 'required',
'primary_phone' => 'required',
]);
Leads::create($request->all());
return redirect()->route('leads.index')
->with('success','Lead created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$leads = Leads::find($id);
return view('leads.show',compact('leads'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$leads = Leads::find($id);
return view('leads.edit',compact('leads'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'first_name' => 'required',
'primary_phone' => 'required',
]);
Leads::find($id)->update($request->all());
return redirect()->route('leads.index')
->with('success','Lead updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
Leads::find($id)->delete();
return redirect()->route('leads.index')
->with('success','Lead deleted successfully');
}
}
You could use url() to go to a url link.
<div class="pull-right">
<div class="btn-group"> <a href="{{ url('leads/create') }}" class="btn btn-info" >Add New</a> </div>
</div>
Or you could use named route
Route::get('leads/create', function () {
return view('Leads.create');
})->name('leads.create');
Create Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Contact;
use Hash;
class ContactController extends Controller
{
public function index(Request $request)
{
$search = $request->get('search');
$field = $request->get('field') != '' ? $request->get('field') : 'first_name';
$sort = $request->get('sort') != '' ? $request->get('sort') : 'asc';
$contacts = new Contact();
$contacts = $contacts->where('first_name', 'like', '%' . $search . '%')
->orderBy($field, $sort)
->paginate(10)
->withPath('?search=' . $search . '&field=' . $field . '&sort=' . $sort);
return view('contacts.index', compact('contacts'))
->with('i', ($request->input('page', 1) - 1) * 10);
}
public function create()
{
return view('contacts.create');
}
public function store(Request $request)
{
$request->validate([
'first_name'=>'required|min:3|max:50',
'last_name'=>'required|min:3|max:50',
'email'=>'required|email|unique:contacts',
'phone' => 'required|numeric|phone',
'password' =>'required|min:3|max:20',
'confirm_password' =>'required|min:3|max:20|same:password'
]);
$contact = new Contact([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name'),
'email' => $request->get('email'),
'job_title' => $request->get('job_title'),
'city' => $request->get('city'),
'country' => $request->get('country'),
'phone' => $request->get('phone'),
'password' => $request->get('password')
]);
$contact->save();
return redirect('/contacts/index')->with('success', 'Contact saved!');
}
public function edit($id)
{
$contact = Contact::find($id);
//print_r($contact);exit;
return view('contacts.edit', compact('contact'));
}
public function update(Request $request, $id)
{
$request->validate([
'first_name'=>'required|min:3|max:50',
'last_name'=>'required|min:3|max:50',
'email'=>'required|email',
'city' => 'required'
]);
$contact = Contact::find($id);
$contact->first_name = $request->get('first_name');
$contact->last_name = $request->get('last_name');
$contact->email = $request->get('email');
$contact->job_title = $request->get('job_title');
$contact->city = $request->get('city');
$contact->country = $request->get('country');
$contact->phone = $request->get('phone');
$contact->password = $request->get('password');
$contact->save();
return redirect('/contacts/index')->with('success', 'Contact updated!');
}
public function delete($id)
{
$contact = Contact::find($id);
$contact->delete();
return redirect('/contacts/index')->with('success', 'Contact deleted!');
}
}
Create Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
protected $fillable = [
'first_name',
'last_name',
'email',
'city',
'country',
'job_title',
'phone',
'password'
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
}
Create routes in web.php
Route::get('contacts/index', 'ContactController#index');
Route::get('contacts/create', 'ContactController#create');
Route::post('contacts/store', 'ContactController#store');
Route::get('contacts/edit/{id}', 'ContactController#edit');
Route::post('contacts/update/{id}', 'ContactController#update');
Route::post('contacts/delete/{id}','ContactController#delete');
Route::post('contacts/index', 'ContactController#index');
create base.blade.php in resources/views folder
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 5.8 & MySQL CRUD Tutorial</title>
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
#yield('main')
</div>
<script src="{{ asset('js/app.js') }}" type="text/js"></script>
</body>
</html>
Create index.blade.php in contacts folder
#extends('base')
#section('main')
<div class="col-sm-12">
#if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div>
#endif
</div>
<div class="row">
<div class="col-sm-12">
<h1 class="display-3">Contacts</h1>
<a class="pull-right btn btn-primary" href="<?php echo url('contacts/create') ?>">Add Contacts</a>
</div>
</div>
<div class="row">
<form action="<?php echo url('contacts/index')?>" method="post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="pull-right btn btn-primary" href="<?php echo url('contacts/index') ?>">view all</button>
<div class="pull-right col-lg-3 input-group custom-search-form">
<input class="form-control" name="search" placeholder="Search..." type="text" value="{{ request('search') }}">
<span class="input-group-btn ">
<button class="btn btn-default" type="submit">
<i class="fa fa-search"></i>
</button>
</span>
</div>
<input type="hidden" value="{{request('field')}}" name="field"/>
<input type="hidden" value="{{request('sort')}}" name="sort"/>
<table class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=first_name&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Name
</a>
{{request('field','first_name')=='first_name'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=email&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Email
</a>
{{request('field','email')=='email'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=job_title&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Job Title
</a>
{{request('field','job_title')=='job_title'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=city&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
City
</a>
{{request('field','city')=='city'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=country&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Country
</a>
{{request('field','country')=='country'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td colspan = 2>Actions</td>
</tr>
</thead>
<tbody>
#foreach($contacts as $contact)
<tr>
<td>{{$contact->id}}</td>
<td>{{$contact->first_name}} {{$contact->last_name}}</td>
<td>{{$contact->email}}</td>
<td>{{$contact->job_title}}</td>
<td>{{$contact->city}}</td>
<td>{{$contact->country}}</td>
<td>
Edit
</td>
<td>
<form action="delete/<?php echo $contact->id?>" method="post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</form>
</div>
#endsection
Create form create.blade.php
#extends('base')
#section('main')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Add a contact</h1>
<div>
<form method="post" action="{{ url('contacts/store') }}">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" class="form-control" name="first_name"/>
<span class="text-danger">{{ $errors->first('first_name') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="last_name">Last Name:</label>
<input type="text" class="form-control" name="last_name"/>
<span class="text-danger">{{ $errors->first('last_name') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="email"/>
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="phone">Phone:</label>
<input type="text" class="form-control" name="phone"/>
<span class="text-danger">{{ $errors->first('phone') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="city">City:</label>
<input type="text" class="form-control" name="city"/>
<span class="text-danger">{{ $errors->first('city') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="country">Country:</label>
<input type="text" class="form-control" name="country"/>
<span class="text-danger">{{ $errors->first('country') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" name="password"/>
<span class="text-danger">{{ $errors->first('password') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="confirm_password">Confrim Password:</label>
<input type="password" class="form-control" name="confirm_password"/>
<span class="text-danger">{{ $errors->first('confirm_password') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="job_title">Job Title:</label>
<input type="text" class="form-control" name="job_title"/>
<span class="text-danger">{{ $errors->first('job_title') }}</span>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Add contact</button>
</form>
</div>
</div>
</div>
#endsection
Create edit.blade.php
#extends('base')
#section('main')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Update a contact</h1>
<form method="post" action="{{ url('contacts/update', $contact->id) }}">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" class="form-control" name="first_name" value="<?php echo $contact->first_name ?>" />
<span class="text-danger">{{ $errors->first('first_name') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="last_name">Last Name:</label>
<input type="text" class="form-control" name="last_name" value="<?php echo $contact->last_name ?>" />
<span class="text-danger">{{ $errors->first('last_name') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="email" value="<?php echo $contact->email ?>" />
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="phone">Phone:</label>
<input type="text" class="form-control" name="phone" value="<?php echo $contact->phone ?>" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="city">City:</label>
<input type="text" class="form-control" name="city" value="<?php echo $contact->city ?>" />
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="country">Country:</label>
<input type="text" class="form-control" name="country" value="<?php echo $contact->country ?>" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="job_title">Job Title:</label>
<input type="text" class="form-control" name="job_title" value='<?php echo $contact->job_title;?>' />
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
</div>
#endsection
Phone number validation put this code in AppServiceProvider.php in boot function
Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
return substr($value, 0, 3) == '+91';
});
Link for Crud Operation - https://www.techiediaries.com/php-laravel-crud-mysql-tutorial/

Image are not showing and cant update my image in laravel

I am doing a project. In this project I want to update name, websit and image field. I want that if a user choose new one then the field upadted otherwise it retains the past value. this works perfectly okay for my name and website_link. But I cant do the image field looking like this. Please help me guys.
My Controller is
public function edit($id)
{
if (Auth::check()) {
if (Auth::user()->user_role->role_id == 1) {
$sponsor = Sponsor::where('id', $id)->first();
if (!empty($sponsor)) {
$data = array(
'menu' => 'sponsor',
'sub_menu' => 'all',
'sponsor' => $sponsor
);
return view('backends.sponsors.edit', $data);
} else {
Session::flash('error', 'Try again.');
return redirect();
}
} else {
return redirect('');
}
} else {
return redirect('');
}
}
public function update(Request $request, $id)
{
if (Auth::check()) {
if (Auth::user()->user_role->role_id == 1) {
$sponsor = Sponsor::where('id', $id)->first();
if (!empty($sponsor)) {
$rules = array(
'name' => '',
'website_link' => '',
'logo' => ''
);
$valid = Validator::make($request->input(), $rules);
if ($valid->fails()) {
return redirect('sponsors/edit/' . $sponsor->id)->withErrors($valid)->withInput();
} else {
$sponsor->name = $request->input('name');
$sponsor->website_link = $request->input('website_link');
// $sponsor->logo = $request->input('logo');
$photo = $request->file('logo');
if($photo)
{
$ext = $photo->getClientOriginalExtension();
$fileName = rand(100, 5000000) . '.' .$ext;
$sponsor->logo = 'public/assets/uploads/sponsors/'.$fileName;
$photo->move(base_path().'/public/assets/uploads/sponsors/',$fileName);
} else {
}
if ($sponsor->save()) {
Session::flash('success', 'Area of experience updated successful.');
return redirect('sponsors/all');
} else {
Session::flash('error', 'Try again.');
return redirect('sponsors/edit//' . $sponsor->id);
}
}
} else {
Session::flash('error', 'Try again.');
return redirect('sponsors/all');
}
} else {
return redirect('');
}
} else {
return redirect('');
}
}
My view page is
#extends ('backends.layouts.app')
#section('main')
<main id="main-container">
<div class="content bg-gray-lighter">
<div class="row items-push">
<div class="col-sm-7">
<h1 class="page-heading">
Sponsors <small>That feeling of delight when you start your awesome new project!</small>
</h1>
</div>
<div class="col-sm-5 text-right hidden-xs">
<ol class="breadcrumb push-10-t">
<li><a class="link-effect" href="{{ URL::to('admin/dashboard') }}">Home</a></li>
<li>Sponsor</li>
</ol>
</div>
</div>
</div>
<div class="content">
<div class="block">
<div class="block-header">
<h3 class="block-title">Sponsor</h3>
</div>
<div class="col-md-12">
#if(Session::has('success'))
<div class="alert alert-success">
<strong> {{ Session::get('success') }}</strong>
</div>
#endif
#if(Session::has('error'))
<div class="alert alert-danger">
<strong> {{ Session::get('error') }}</strong>
</div>
#endif
</div>
<div class="clearfix"></div>
<div class="block-content">
<form method="POST" action="{{ (!empty($sponsor->id)) ? URL::to('sponsors/edit/'.$sponsor->id) : '' }}" class="push-10-t" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<div class="form-material floating">
<input type="text" name="name" value="{{ (!empty($sponsor->name)) ? $sponsor->name : old('name') }}" id="name" class="form-control" required >
<label for="name">Company Name</label>
</div>
</div>
<div class="form-group">
<div class="form-material floating">
<input type="text" name="website_link" value="{{ (!empty($sponsor->website_link)) ? $sponsor->website_link : old('name') }}" id="website_link" class="form-control" >
<label for="website_link">Website Link</label>
</div>
</div>
<div class="form-group">
<label for="logo">Logo</label><br/>
<div id="prev" style="display: none" class="col-md-3 thumbnail">
<img id="blah" class="img-responsive">
</div>
<div class="clearfix"></div>
<div class="form-group">
<label for="logo"> <span class="btn btn-primary" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : old('logo') }}" id="fileName0">Browse</span></label>
<input type="file" name="logo" style="visibility: hidden; position: absolute;" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : old('logo') }}" id="logo" class="form-control" required>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
</div>
</div>
</div>
</main>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#logo").change(function(){
$('#prev').show();
readURL(this);
});
</script>
#endsection
Please help me solving this
The answer will be
public function update(Request $request, $id)
{
if (Auth::check()) {
if (Auth::user()->user_role->role_id == 1) {
$sponsor = Sponsor::where('id', $id)->first();
if (!empty($sponsor)) {
$rules = array(
'name' => 'required',
'website_link' => 'required',
'logo' => ''
);
$valid = Validator::make($request->input(), $rules);
if ($valid->fails()) {
return redirect('sponsors/edit/' . $sponsor->id)->withErrors($valid)->withInput();
} else {
$sponsor->name = $request->input('name');
$sponsor->website_link = $request->input('website_link');
$hdLogo = $request->input('hdLogo');
$photo = $request->file('logo');
if(!empty($photo) && !empty($hdLogo)){
$ext = $photo->getClientOriginalExtension();
$fileName = rand(100, 5000000) . '.' .$ext;
$sponsor->logo = 'public/assets/uploads/sponsors/'.$fileName;
$photo->move(base_path().'/public/assets/uploads/sponsors/',$fileName);
}else if(!empty($photo) && empty($hdLogo)){
$ext = $photo->getClientOriginalExtension();
$fileName = rand(100, 5000000) . '.' .$ext;
$sponsor->logo = 'public/assets/uploads/sponsors/'.$fileName;
$photo->move(base_path().'/public/assets/uploads/sponsors/',$fileName);
}else if(empty($photo) && !empty($hdLogo)){
$sponsor->logo = $sponsor->logo;
}
else if(empty($photo) && empty($hdLogo)){
Session::flash('error','Logo is required.');
return redirect()->back();
}
if ($sponsor->save()) {
Session::flash('success', 'Sponsor updated successful.');
return redirect('sponsors/all');
} else {
Session::flash('error', 'Try again.');
return redirect()->back();
}
}
} else {
Session::flash('error', 'Try again.');
return redirect('sponsors/all');
}
} else {
return redirect('');
}
} else {
return redirect('');
}
}
And the view file will be
#extends ('backends.layouts.app')
#section('main')
<main id="main-container">
<div class="content bg-gray-lighter">
<div class="row items-push">
<div class="col-sm-7">
<h1 class="page-heading">
Sponsors <small>That feeling of delight when you start your awesome new project!</small>
</h1>
</div>
<div class="col-sm-5 text-right hidden-xs">
<ol class="breadcrumb push-10-t">
<li><a class="link-effect" href="{{ URL::to('admin/dashboard') }}">Home</a></li>
<li>Sponsor</li>
</ol>
</div>
</div>
</div>
<div class="content">
<div class="block">
<div class="block-header">
<h3 class="block-title">Sponsor</h3>
</div>
<div class="col-md-12">
#if(Session::has('success'))
<div class="alert alert-success">
<strong> {{ Session::get('success') }}</strong>
</div>
#endif
#if(Session::has('error'))
<div class="alert alert-danger">
<strong> {{ Session::get('error') }}</strong>
</div>
#endif
</div>
<div class="clearfix"></div>
<div class="block-content">
<form method="POST" action="{{ (!empty($sponsor->id)) ? URL::to('sponsors/edit/'.$sponsor->id) : '' }}" class="push-10-t" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<div class="form-material floating">
<input type="text" name="name" value="{{ (!empty($sponsor->name)) ? $sponsor->name : old('name') }}" id="name" class="form-control" required >
<label for="name">Company Name</label>
</div>
</div>
<div class="form-group">
<div class="form-material floating">
<input type="text" name="website_link" value="{{ (!empty($sponsor->website_link)) ? $sponsor->website_link : old('name') }}" id="website_link" class="form-control" >
<label for="website_link">Website Link</label>
</div>
</div>
<div class="form-group">
<label for="logo">Logo</label><br/>
<input type="hidden" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : ''}}" name="hdLogo">
#if(!empty($sponsor->logo))
<div id="prev" class="col-md-3 thumbnail">
<img id="blah" src="{{ url($sponsor->logo)}}" class="img-responsive">
</div>
#else
<div id="prev" style="display: none" class="col-md-3 thumbnail">
<img id="blah" src="{{ (!empty($sponsor->logo)) ? $sponsor->logo : '' }}" class="img-responsive">
</div>
#endif
<div class="clearfix"></div>
<div class="form-group">
#if(!empty($sponsor->logo))
<label for="logo"> <span class="btn btn-primary" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : old('logo') }}" id="fileName0">Browse</span></label>
<input type="file" name="logo" style="visibility: hidden; position: absolute;" id="logo" class="form-control">
#else
<label for="logo"> <span class="btn btn-primary" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : old('logo') }}" id="fileName0">Browse</span></label>
<input type="file" name="logo" style="visibility: hidden; position: absolute;" id="logo" class="form-control" required>
#endif
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
</div>
</div>
</div>
</main>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#logo").change(function(){
$('#prev').show();
readURL(this);
});
</script>
#endsection

Validation error message not showing and datas not being saved to database

I am trying to first validate the inputs and then add the values to database but neither I am able to see the validation error message nor I am able to insert records to database. I have a table in database named 'news' where I have
this is my boxed.blade.php
<form class="form-horizontal" role="form" method="post" action="/addNews" novalidate>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 col-sm-2 control-label">Title</label>
<div class="col-lg-10">
<input type="text" name="title" class="form-control" id="inputEmail1" placeholder="News Title" value="{{ Input::old('title') }}">
</div>
</div>
<div class="form-group">
<label for="inputPassword1" class="col-lg-2 col-sm-2 control-label">Description</label>
<div class="col-lg-10">
<textarea name="description" class="form-control" rows="6">{{ Input::old('description') }}</textarea>
</div>
</div>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 col-sm-2 control-label">Reporter</label>
<div class="col-lg-10">
<input type="text" name="reported_by" class="form-control" id="inputEmail1" placeholder="Reporter Name" value="{{ Input::old('reported_by') }}">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<div class="checkbox">
<label>
<input type="checkbox" name="status"> Status
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-danger"><i class="fa fa-comments"></i> Add To List</button>
</div>
</div>
</form>
And routes.php
Route::get('addNews', function()
{
return View::make('pages.boxed');
}
);
Route::post('addNews', function()
{
//processing the form
$rules = array(
'title' => 'required',
'description' => 'required|min:50',
'reported_by' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()){
$message = $validator->message();
return Redirect::to('addNews')->withErrors($validator)->withInput(Input::all());
}
else{
$news = new News;
$news->title = Input::get('title');
$news->description = Input::get('description');
$news->reported_by = Input::get('reported_by');
$news->status = Input::get('status');
$news->save();
return Redirect::to('addNews');
}
}
This is my model News.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class News extends Model
{
protected $fillable = array('title', 'description', 'reported_by', 'status');
}
If you want to see the error, place the following code above your form:
#if (count($errors) > 0)
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
UPDATE 1: Instead of defining the methods in routes.php file, define it in a Controller called NewsController
So, to do this, update your routes.php file to this:
Route::get('/addNews', 'getNewsForm');
Route::post('/addNews', 'postNewsForm');
NewsController.php
/**
* Display the add news form to the user.
*
* #return view
*/
public function getNewsForm()
{
return View::make('pages.boxed');
}
/**
* Store the input in the database after validation
*
* #param $request Illuminate\Http\Facade\Request
*/
public function postNewsForm(Request $request)
{
$this->validate($request, [
'title' => 'required',
'description' => 'required|min:50',
'reported_by' => 'required'
]);
News::create($request->all());
return redirect('/addNews');
}

Categories