In this tutorial, we will learn how to update profile image with AJAX in Laravel.
Many times we need to update or upload profile image, or any images without refreshing the page, so there we will use AJAX.
Step 1: Install Laravel via composer
First of all we need to install laravel via composer using the below command.
composer create-project laravel/laravel laravel-ajax
After installation go to your project directory. In my case my project directory name is laravel-ajax so i am going to this directory by cd laravel-ajax.
Step 2: Create Routes
Open web.php
file and create routes
laravel-ajax\routes\web.php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/',[UserController::class,'index'])->name('index');
Route::post('add-user',[UserController::class,'add_user'])->name('add-user');
Route::post('update-image',[UserController::class,'update_image'])->name('update-image');
Step 3 – Create Model
Create User model run below command in your terminal
php artisan make:model User
laravel-ajax\app\Models\User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasFactory;
protected $fillable = [
'name',
'email',
'profile',
'password',
];
}
Step 4- Make controller
Create a controller using the below command in your terminal.
php artisan make:controller UserController
laravel-ajax\ app\ Http\ Controllers\ UserController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index(){
$users = User::all();
return view('index',compact('users'));
}
public function add_user(Request $request){
$img_name = 'img_'.time().'.'.$request->profile->getClientOriginalExtension();
$request->profile->move(public_path('img/'), $img_name);
$imagePath = 'img/'.$img_name;
$data = [
'name'=>$request->name,
'profile'=>$imagePath,
'email'=>$request->email,
'password'=>$request->password,
];
$add = User::create($data);
if($add){
$response['success'] = true;
$response['message'] = 'Success! Record Added Successfully.';
}else{
$response['success'] = false;
$response['message'] = 'Error! Record Not Added.';
}
return $response;
}
public function update_image(Request $request){
$img_name = 'img_'.time().'.'.$request->profile->getClientOriginalExtension();
$request->profile->move(public_path('img/'), $img_name);
$imagePath = 'img/'.$img_name;
$data = [
'profile'=>$imagePath,
];
$update = User::find($request->user_id)->update($data);
if($update){
$response['success'] = true;
$response['message'] = 'Success! Record Updated Successfully.';
}else{
$response['success'] = false;
$response['message'] = 'Error! Record Not Updated.';
}
return $response;
}
}
Step 5- Create blade file
Create index.blade.php
file
laravel-ajax\ resources\ views\ index.blade.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>Laravel-ajax</title>
<style>
body {
background: rgb(174, 182, 255);
}
.profileImg img {
height: 150px;
max-width: 200px;
}
</style>
</head>
<body>
<div class="container mt-5 bg-white pb-3">
<div class="row bg-white">
<div class="col px-4 py-3">
<div class="row">
<div class="col-md-9">
<h3 class="">Laravel-Ajax Image Upload Example</h3>
</div>
<div class="col-md-3 ">
<button class="btn btn-success float-md-right" data-toggle="modal"
data-target="#exampleModalCenter">Add New User</button>
</div>
</div>
<hr>
</div>
</div>
<div class="">
<div class="alert alert-danger" role="alert" id="failedMessage" style="display: none"></div>
<div class="alert alert-success" role="alert" id="successMessage" style="display: none"></div>
</div>
<div class="row pr-md-5">
@if (count($users) > 0)
<div class="col-md-4">
<div class="list-group" id="list-tab" role="tablist">
@foreach ($users as $key=>$user)
<a class="list-group-item list-group-item-action {{ $key ? '':'active' }}" id="list-{{ $key }}-list"
data-toggle="list" href="#list-{{ $key }}" user_id="{{ $user->id }}" role="tab"
aria-controls="{{ $key }}">{{ $user->name }}</a>
@endforeach
</div>
</div>
<div class="col-md-8">
<div class="tab-content" id="nav-tabContent">
@foreach ($users as $key=>$user)
<div class="tab-pane fade show {{$key ? '':'active'}}" id="list-{{ $key }}" role="tabpanel"
aria-labelledby="list-{{ $key }}-list">
<div class="">
<h5>User Detail</h5>
<hr>
<div class="row">
<div class="col-md-4">
<div class="profileImg ">
<img class="border p-2" src="{{ asset($user->profile) }}" alt="profile image">
<input type="file" id="updateImage" hidden>
<br>
<button class="btn btn-primary mt-3"><label for="updateImage">Update
Image</label></button>
</div>
</div>
<div class="col-md-8">
<label for="">Full Name :</label><br>
<input type="text" class="form-control" disabled value="{{ $user->name }}">
<label for="">Email Address :</label><br>
<input type="text" class="form-control" disabled value="{{ $user->email }}">
<label for="">Password :</label><br>
<input type="text" class="form-control" disabled value="{{ $user->password }}">
</div>
</div>
</div>
</div>
@endforeach
</div>
</div>
@else
<div class="col">
<p class="text-center">Oops! Record Not Found.</p>
</div>
@endif
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog"
aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Enter User Detail</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="POST" id="addNewUser" enctype="multipart/form-data">
@csrf
<div class="form-group">
<label for="fullname">Full Name</label>
<input type="text" class="form-control" name="" id="fullname" placeholder="Enter full name">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" name="email" class="form-control" id="email"
aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control" id="password"
placeholder="Password">
</div>
<div class="form-group">
<label for="file">Example file input</label>
<input type="file" name="profile" accept="image/*" class="form-control-file" id="file">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
@php
if(count($users) > 0){
$user_id = $users[0]->id;
}else{
$user_id = '';
}
@endphp
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
</script>
<script>
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
let profile;
const user_id = "{{ $user_id }}";
$('#file').change(function (e) {
profile = e.target.files[0];
})
$('#updateImage').change(function (e) {
profile = e.target.files[0];
var formData = new FormData();
formData.append('profile', profile);
formData.append('user_id', user_id);
$.ajax({
cache: false,
contentType: false,
processData: false,
type: 'post',
data: formData,
url: "{{ route('update-image') }}",
success: function (response) {
if (response.success) {
$('#successMessage').show();
$('#successMessage').text(response.message);
} else {
$('#failedMessage').show();
$('#failedMessage').text(response.message);
}
setTimeout(() => {
location.reload();
}, 2000);
}
});
});
$('#addNewUser').submit(function (e) {
e.preventDefault();
var name = $('#fullname').val();
var email = $('#email').val();
var password = $('#password').val();
var formData = new FormData();
formData.append('profile', profile);
formData.append('name', name);
formData.append('email', email);
formData.append('password', password);
$.ajax({
cache: false,
contentType: false,
processData: false,
type: 'post',
data: formData,
url: "{{ route('add-user') }}",
success: function (response) {
$('#exampleModalCenter').modal('hide');
if (response.success) {
$('#successMessage').show();
$('#successMessage').text(response.message);
} else {
$('#failedMessage').show();
$('#failedMessage').text(response.message);
}
setTimeout(() => {
location.reload();
}, 2000);
}
});
})
$('.list-group-item-action').click(function () {
user_id = $(this).attr('user_id');
});
</script>
</body>
</html>
Step 6- Create users table
Create a users table using migration or directly from your database.
Here is the schema for the users migration table .
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('profile')->nullable();
$table->string('password');
$table->timestamps();
});
Step 7 – Run php artisan serve
Output-
Leave a comment