NotWritableException Can't write image data to path - php

How to store an avatar correctly
(in developer mode) The way I have my Controller now
it stores the new image path to the database but doesn't upload it to the 'uploads/avatars' folder.
Also when I try to just edit the profile without uploading a new avatar, it throws an ErrorException undefined variable:avatar,
and the version i have on my hosting server also throws the Errorexception if not uploading but only editing the profile,
And if I try to upload a new avatar it tells me
NotWritableException
Can't write image data to path (/home/vlindr.com/vlindr/public/uploads/avatars/1504691841.jpg)
Anybody knows how to go about fixing this?
My Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
use Session;
use Image;
use Illuminate\Support\Facades\File;
use App\User;
use DB;
use Illuminate\Support\Facades\Storage;
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth', ['except' => ['index', 'show']]);
}
//
public function index(){
return view('profiles.profile', array('user' => Auth::user()) );
}
public function edit()
{
return view('profiles.edit')->with('info', Auth::user()->profile);
}
public function update(Request $request)
{
$this->validate($request, [
'location' => 'required',
'about' => 'required|max:355',
'passion' => 'required|max:355'
]);
Auth::user()->profile()->update([
'location' => $request->location,
'about' => $request->about,
'passion' => $request->passion
]);
$user = User::find(Auth::user()->id);
// Handle the user upload of avatar
if ($request->hasFile('avatar')) {
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
}
// Delete current image before uploading new image
if ($user->avatar !== 'man.png' && $user->avatar !== 'woman.png')
{
$file = public_path('/uploads/avatars/' . $user->avatar);
if (File::exists($file)) {
unlink($file);
}
}
Image::make($avatar->getRealPath())->resize(350, 350)->save( public_path('/uploads/avatars/' . $filename ) );
$user = Auth::user();
$user->avatar = $filename;
$user->save();
return back()->with('msg', 'Profiel is bijgewerkt');
}
}

Related

images do not display in Laravel 8

am trying to store images in storage folder in Laravel 8 and at the same time fetch that image and displays it in browser, unfortunately, the images get saved but do not display
here is my file
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class PostsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function create(){
return view('posts.create');
}
public function store(){
$data = request()->validate([
'caption' => 'required',
'image' => ['required','image']
]);
$imagePath = request('image')->store('uploads','public');
$image = Image::make(public_path("{C:\xampp\htdocs\app\storage\app\public\uploads\
{$imagePath}"))->fit(1000,1000);
$image->save();
dd($imagePath);
auth()->user()->posts()->create([
'caption' => $data['caption'],
'image'=>$imagePath,
]);
return redirect('/profile/'. auth()->user()->id);
}
public function show(\App\Models\Post $post){
return view('posts.show', compact('post'));
}
}
any help guys

Code for Facebook and Google Login not working on live server

Laravel version : 7.9.2
PHP version: 7.4
I have code for login with Facebook and Google. It's working absolutely fine on localhost but on live server it doesn't work. Surprising thing is It neither returns any error nor throw any exception.
It simply redirect user back to login page and my URL shows the string #=.
This is live link
https://beta.car-chain.net/login
I need suggestion.
LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use App\User;
use Exception;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected $providers = [
'github','facebook','google','twitter'
];
public function show()
{
return view('auth.login');
}
public function redirectToProvider($driver)
{
if( ! $this->isProviderAllowed($driver) ) {
return $this->sendFailedResponse("{$driver} is not currently supported");
}
try {
return Socialite::driver($driver)->redirect();
} catch (Exception $e) {
// You should show something simple fail message
return $this->sendFailedResponse($e->getMessage());
}
}
public function handleProviderCallback( $driver )
{
try {
$user = Socialite::driver($driver)->user();
} catch (Exception $e) {
return $this->sendFailedResponse($e->getMessage());
}
// check for email in returned user
return empty( $user->email )
? $this->sendFailedResponse("No email id returned from {$driver} provider.")
: $this->loginOrCreateAccount($user, $driver);
}
protected function sendSuccessResponse()
{
return redirect()->intended('home');
}
protected function sendFailedResponse($msg = null)
{
return redirect()->route('social.login')
->withErrors(['msg' => $msg ?: 'Unable to login, try with another provider to login.']);
}
protected function loginOrCreateAccount($providerUser, $driver)
{
// check for already has account
$user = User::where('email', $providerUser->getEmail())->first();
// if user already found
if( $user ) {
// update the avatar and provider that might have changed
$user->update([
'provider' => $driver,
'provider_id' => $providerUser->id,
'access_token' => $providerUser->token
]);
} else {
if($providerUser->getEmail()){ //Check email exists or not. If exists create a new user
$user = User::create([
'name' => $providerUser->getName(),
'email' => $providerUser->getEmail(),
'provider' => $driver,
'provider_id' => $providerUser->getId(),
'access_token' => $providerUser->token,
'password' => '' // user can use reset password to create a password
]);
}else{
//Show message here what you want to show
}
}
// login the user
Auth::login($user, true);
return $this->sendSuccessResponse();
}
private function isProviderAllowed($driver)
{
return in_array($driver, $this->providers) && config()->has("services.{$driver}");
}
}
Route.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('auth/social', 'Auth\LoginController#show')->name('social.login');
Route::get('oauth/{driver}', 'Auth\LoginController#redirectToProvider')->name('social.oauth');
Route::get('oauth/{driver}/callback', 'Auth\LoginController#handleProviderCallback')->name('social.callback');

How can I post several images from this Controller?

Basic Information
I'm developing a simple Web Application that it can post photo using Laravel.
My Question
I want to create several image post form using another variable.
How can I make work my Controllers using another variable?
My Codes
routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| 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('login');
Route::group(['middleweare' => 'auth'], function () {
Route::get('/', 'StoriesController#index');
Route::post('/', 'StoriesController#store');
Route::get('/stories/create', 'StoriesController#add');
Route::post('/stories/create', 'StoriesController#uplaod');
});
Route::group(['middleweare' => 'auth','name'=>'profile'], function () {
Route::get('/profile/edit', 'ProfileController#edit');
Route::get('/profile/create', 'ProfileController#add');
Route::post('/profile/create', 'ProfileController#store');
Route::post('/profile/create', 'ProfileController#upload');
});
Route::get('/home', 'HomeController#index')->name('home');
Auth::routes();
app/Http/Controllers/StoriesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Story;
use Auth;
use App\Posts;
use App\History;
use App\Attachment;
use Carbon\Carbon;
use Storage;
class StoriesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
$images = Attachment::all();
return view('stories.index2', compact('images'));
}
public function add()
{
return view('stories.create2');
}
public function store(Request $request)
{
$d = new \DateTime();
$d->setTimeZone(new \DateTimeZone('Asia/Tokyo'));
$dir = $d->format('Y/m');
$path = sprintf('public/images/%s', $dir);
$data = $request->except('_token');
foreach ($data['images'] as $k => $v) {
$filename = '';
$attachments = Attachment::take(1)->orderBy('id', 'desc')->get();
foreach ($attachments as $attachment) {
$filename = $attachment->id + 1 . '_' . $v->getClientOriginalName();
}
unset($attachment);
if ($filename == false) {
$filename = 1 . '_' . $v->getClientOriginalName();
}
$v->storeAs($path, $filename);
$attachment_data = [
'path' => sprintf('images/%s/', $dir),
'name' => $filename
];
$a = new Attachment();
$a->fill($attachment_data)->save();
}
unset($k, $v);
return redirect('/');
}
public function upload(Request $request)
{
dd($request->all());
$this->validate($request, [
'file' => [
'required',
'file',
'image',
'mimes:jpeg,png',
]
]);
if ($request->file('file')->isValid([])) {
$path = $request->file->store('public');
return view('stories.index2')->with('filename', basename($path));
} else {
return redirect('/')
->back()
->withInput()
->withErrors();
}
}
}
I made a profile image post form, and general image post form.
And I want to view those image on same page.

Call to undefined method Illuminate\Database\Eloquent\Builder::save()

So, what i`m trying to do here is to save an image to an specific user that is logged in. and it gives me this error
<?php
namespace App\Http\Controllers\Auth;
use Auth;
use Illuminate\Http\Request;
use App\Models\ProfileEmployee;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
class ImageUploadController extends Controller
{
public function index()
{
$profilasdeimage = ProfilasdeEmployee::where('uid', Auth::user()->id)->first();
return vieasdw('editareemasdployee', compact('profileiasdmage'));
}
public function store(Requasdest $request)
{
$emplasdoyee = ProfileEasdmployee::where('uiasdd', Autasdh::user()->id);
if ($request->hasfile('imasdage')){
$file = $request->file('image');
$exteasdnsion = $file->getClientOriginalExtension();
$fileasdname = md5(time()).'.'.$extension;
$fiasdle->move('public/imaginasdeprofil',$filename);
$empasdloyee->imagasde=$filename;
} else {
return $request;
$emplasdoyee->imasdage='';
}
$emplasdoyee->save(); --->> this is the problem
return view('imageuplasdoad')->with('profasdileimage',$emplasdoyee);
}
}
i want to use this database table to fill the 'image' using the id provided from table users as uid in this table
protected $filasdlable = [
'iasdd', 'uiasdd', 'fasdirst_nasdame', 'lasdast_nasdame','phasdone', 'casdv', 'imasdage', 'addasdress', 'ciasdty',
];
Add first() to your query or use find:
$employee = ProfileEmployee::where('uid', Auth::user()->id)->first();

is this Laravel Relationship error undefined variable $task

I am developing project management app in Laravel 5.2. in My application I have one project many tasks and one task have many file attachments. this is My file attachment view file
#foreach($task->files as $file) //line 14
<div>
<div><i class="fa fa-check-square-o"></i>
<span>
{{ $file->file_name }}
</span>
</div>
</div>
and My FileController is this
use Cloudder;
use App\File as File;
use App\Task;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class FilesController extends Controller
{
public function uploadAttachments(Request $request,$id,$taskId)
{
$this->validate($request, [
'file_name' => 'required|mimes:jpeg,bmp,png,pdf|between:1,7000',
]);
$filename = $request->file('file_name')->getRealPath();
Cloudder::upload($filename, null);
list($width, $height) = getimagesize($filename);
$fileUrl = Cloudder::show(Cloudder::getPublicId(), ["width" => $width, "height" => $height]);
$this->saveUploads($request, $fileUrl, $id,$taskId);
and route is this
Route::post('projects/{projects}/tasks/{tasks}/', [
'uses' => 'FilesController#uploadAttachments',
'as' => 'projects.files',
'middleware' => ['auth']
]);
but got this error
ErrorException in ae0a86ab95cb7f092eb44a17fd000e94f21b305d.php line 14:
Undefined variable: task (View: C:\Users\13\Desktop\acxian\resources\views\files\form.blade.php)
how can fix this problem?
file Model
use Auth;
use App\Task;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
public function scopeProject($query, $id)
{
return $query->where('project_id', $id);
}
public function scopeTask($query, $taskId)
{
return $query->where('task_id', $taskId);
}
public function task(){
return $this->belongsTo(Task::class);
}
You have to pass the $task collection to your blade view as shown below
$task = Task::all() //collect task collection as per your logic
return view('files.form', compact('task'));
You have to pass $task data to your view (blade file) like this
return view('files.form', $task);
public function show($project_id,$task_id) {
$project = Project::find($project_id);
$task = Task::find($task_id);
return view('task.show', ['task' => $task,'project' => $project]);
}

Categories