images do not display in Laravel 8 - php

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

Related

The get () function not working on laravel 8 updated version

This is the ArticlesController code
<?php
namespace App\Http\Controllers;
use App\Models\Article;
use Illuminate\Http\Request;
class ArticlesController extends Controller
{
public function index()
{
$articles = Article::latest()->get();
return view('articles.index', ['articles' => $articles]);
}
public function show($id)
{
$article = Article::find($id);
return view('articles.show', ['article' => $article]);
}
}
And this is the web.php code
Route::get('/articles', 'App\Http\Controllers\ArticlesController#index');
and this is the layout.blade.php code
<li class={{Request::path() === 'articles' ? 'current_page_item' : ''}}><a href="/articles"
accesskey="4"
I tried so many different ways and it's working but in laravel 8 it's not.
public function index()
{
$articles = Article::query()->latest()->get();
return view('articles.index', ['articles' => $articles]);
}

Base table or view not found: 1146 Table 'admin.model' doesn't exist

How to fix this error. I am trying to update data in table.
This is my controller
public function update($id)
{
$input = request()->all();
return response()->json(['success' => true], 200);
}
This is my model
namespace App\Models\Models;
use Illuminate\Database\Eloquent\Model;
class ModelsCategory extends Model
{
protected $table = 'models_categories';
protected $guarded = ['id'];
}
You have not made any updates within the function
Make changes like me
public function update(Requeat $request, $id)
{
ModelsCategory::where("id",$id)->update([
// Herer set your column and data like this
'tiltle'=>$request->title,
]);
return response()->json(['success' => true], 200);
}
Or you can use this.
first change route like this:
Route::post("/category/{modelscategory}","categorycontroller#update")
update mthod
public function update(Requeat $request, ModelsCategory $modelscategory)
{
$modelscategory->title=$request->title;
$modelscategory->save();
return response()->json(['success' => true], 200);
}
I hope I helped

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]);
}

NotWritableException Can't write image data to path

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');
}
}

Sanitizing preg_match via Request in Laravel 5 not working as it should

I have a feature where I sanitize a YouTube link before it gets saved to the database. I have the preg_match working fine, but I can't pass the sanitized version (just the YouTube ID) back to the Controller, it reverts back the unsanitised original link.
VideoRequest:
public function rules()
{
$this->sanitize();
return [
'page_id' => 'required|integer',
'visibility' => 'required',
'item_type' => 'required',
'title' => 'required|string',
'embed' => 'required',
'content' => '',
'image' => 'string',
'order' => 'required|integer'
];
}
public function sanitize()
{
$input = $this->all();
if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $input['embed'], $match)) {
$input['embed'] = $match[1];
} else {
return "Please try another YouTube URL or link";
}
$this->replace($input);
}
VideoController:
public function store(VideoRequest $request)
{
$video = array_intersect_key(Input::all(), $request->rules());
VideoItem::create($video);
flash()->success('New video created');
return redirect()->back();
}
When I dd($input) at the bottom of sanitize() function it will return all inputs with the embed code correctly, just as an ID. When it passes to rules(); embed is now the original link?
Maybe use a custom validation rule and then a mutator to extract the YouTube id just before the model save.
http://laravel.com/docs/5.0/validation#custom-validation-rules
http://laravel.com/docs/5.0/eloquent#accessors-and-mutators
Routes
Route::post('post', 'PostController#store');
/**
* Extract Youtube id from url
* #todo: move to helpers file
*/
function sanitiseHelper ($value) {
if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $value, $match)) {
return $match[1];
}
return false;
}
Controller
namespace App\Http\Controllers;
use App\Post;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PostController extends Controller
{
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
Validator::extend('sanitise', function($attribute, $value, $parameters)
{
return sanitiseHelper($value);
});
$validator = Validator::make($request->all(), [
'YoutubeUrl' => 'sanitise'
], ['sanitise' => 'Please try another YouTube URL or link']);
if ($validator->fails()) {
return $validator->errors()->all();
}
// Save
Post::create($request->all());
}
}
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function setYouTubeUrlAttribute($value)
{
$this->attributes['YouTubeUrl'] = sanitiseHelper($value);
}
}
I use
/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/
to get the ID.

Categories