I am using a observer class to store image, everything works fine e.g. images are store in public folder, save in database but after the saving it will give me a error like below
I tried this in my Student observer class
protected $request;
public function __construct(Register $request)
{
$this->request = $request;
}
public function created(Student $student)
{
//
}
public function creating(Student $student)
{
//dd($request->image);
if ($this->request->hasFile('image')) {
$file = $this->request->image;
$destinationPath = public_path().'/images/';
$filename= $student->username . '.'.$file->clientExtension();
$file->move($destinationPath, $filename);
$student->image=$filename;
}
}
And in my controller
public function create(Register $request)
{
$student=new Student;
$student->name = $request->input('name');
$student->username = $request->input('username');
$student->email = $request->input('email');
$student->password = bcrypt($request->input('password'));
$student->gender = $request->input('gender');
$student->phone = $request->input('phone');
$student->save();
$student->subjects()->attach($request->id);
return home('home');
}
Related
I have three tables in my database(users,cars and photos).
Users Table
Cars Table
Photos Table
My Models:
User.php
public function photo() {
return $this->morphOne('App\Models\Photo', 'imageable');
}
public function cars() {
return $this->hasMany('App\Models\Car', 'user_id');
}
Car.php
public function user() {
return $this->belongsTo('App\Models\User');
}
public function photo() {
return $this->morphOne('App\Models\Photo', 'imageable');
}
Photo.php
protected $path = '/storage/images/';
public function getFileAttribute($file) {
return $this->path . $file;
}
public function imageable() {
return $this->morphTo();
}
My Controller#store:
$input = $request->all();
$user = Auth::user();
if ($file = $request->file('photo_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('storage/images', $name);
$photo = Photo::create(['file' => $name]);
$input['photo_id'] = $photo->id;
}
$user->cars()->create($input);
return back();
Imageable_id and imageable_type aren't storing. Just NULL. Why? How to store it?
You're not using the relationship when you create the photo.
$photo = Photo::create(['file' => $name]);
It should be:
$photo = $user->photo()->create(['file' => $name]);
Also, $user->cars()->create(...) instead of $user->cars->create(...)
This is my previous post: Laravel inserting normal image, value become null
Thank you for everyone giving me advise in previous post. Now I got another question. I would like to ask for help and teach me with this issues.
I currently want to save the image path in my database. As the previous post mentioned before. My database now is saving value 1 instead of the path. here is my function upload code.
public function upload(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$task->image = \Storage::disk('public')->put('image', Request::file('image'));
$url = Storage::url('image');
$url= urldecode(string ($url));
$url->save();
$task->save();
return redirect('/');
}
I also want to display this in my welcome.blade.php. So, what would I add and change?
This is all my code:
public function index()
{
$user = Auth::user();
return view('welcome',compact('user'));
}
public function add()
{
return view('add');
}
public function create(Request $request)
{
$task = new Task();
$task->description = Request::get('description');
$task->user_id = Auth::id();
$flagInserted = \Storage::disk('public')->put('image', Request::file('image'));
$url = '';
if ($flagInserted) {
$url = Storage::url('image');
}
$task->image = $url;
$duplicate = Task::where('description',Request::get('description'))->first();
if($duplicate)
{
print_r("The data is exists");
}
else
{
$task->save();
}
return redirect('/');
}
public function edit(Task $task)
{
if (Auth::check() && Auth::user()->id == $task->user_id)
{
return view('edit', compact('task'));
}
else {
return redirect('/');
}
}
public function update(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$task->description = Request::get('description');
$task->save();
return redirect('/');
}
}
public function upload(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$flagInserted = \Storage::disk('public')->put('image', Request::file('image'));
$url = '';
if ($flagInserted) {
$url = Storage::url('image');
}
$task->image = $url;
$task->save();
return redirect('/');
}
}
public function storeTask(){
$task= new Task();
$task->name = request('name');
$task->description = request('description');
$task->image = request('image');
$task->save();
return redirect('/task');
}
I have read the Laravel page. But not really sure and how can I able solve this problem.
below will return 1 or 0, if file is saved or not. That's why it is inserting 1 into your databse:
\Storage::disk('public')->put('image', Request::file('image'))
Once successfully saved, To fetch file url, you can use below code:
$url = \Storage::url('file.jpg');
So your code will be:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FileuploadController extends Controller
{
//
public function index() {
return view('fileupload');
}
public function save(Request $request) {
$image = $request->file('image');
$fileName = time() . '.' . $image->getClientOriginalExtension();
$img = \Image::make($image->getRealPath());
$img->stream(); // <-- Key point
$flagInserted = \Storage::disk('public')->put($fileName, $img);
$url = '';
if ($flagInserted) {
$url = \Storage::url('app/public/' . $fileName);
}
dd($url);
}
}
If you face error like 'Class Image' not found that do as follow:
composer require intervention/image
You file will be saved in 'storage/app/public folder'.
If you file is not saved than please permission and allow permission your project folder.
have you try this.? Request::file to $request->file
and
replce Illuminate\Support\Facades\Request to use Illuminate\Http\Request;
ref link https://laravel.com/docs/6.x/filesystem#file-uploads here you can see
use Illuminate\Http\Request; is imported not Illuminate\Support\Facades\Request
public function upload(Request $request, Task $task)
{
if (isset($_POST['delete'])) {
$task->delete();
return redirect('/');
} else {
$task->image = \Storage::disk('public')->put('image', $request->image);
$task->save();
return redirect('/');
}
}
ref link https://laravel.com/docs/6.x/filesystem#storing-files
and to print image inside blade
you can use Storage::url() function on laravel
EX : Storage::url($task->image) // here image value is coming from task table data
ref link https://laravel.com/docs/6.x/filesystem#file-urls
I am trying to store an image in my images table that is related to the articles table
When I do this the following error appears:
Indirect modification of overloaded property App\Article::$thumbnail has no effect.
My Article Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
protected $fillable = [
'title', 'exerpt', 'body'
];
public function author()
{
return $this->belongsTo(User::class, 'user_id');
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
public function thumbnail()
{
return $this->hasOne(Image::class);
}
}
My Image Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function article()
{
return $this->belongsTo(Article::class);
}
}
And the store method in my ArticleController:
public function store(Request $request)
{
$article = new Article($this->validateArticle($request));
//hardcoded for now
$article->user_id = 1;
$thumbnail = '';
$destinationPath = storage_path('app/public/thumbnails');
$file = $request->thumbnail;
$fileName = $file->clientExtension();
$file->move($destinationPath, $fileName);
$article->thumbnail->title = $file;
$article->save();
$article->tags()->attach(request('tags'));
return redirect(route('articles'));
}
Related to your Laravel version, this may works for you:
$article = new Article( $this->validateArticle( $request ) );
$article->user_id = 1;
$article->save();
$article->tags()->attach( request( 'tags' ) );
if( $request->hasFile( 'thumbnail' ) ) {
$destinationPath = storage_path( 'app/public/thumbnails' );
$file = $request->thumbnail;
$fileName = time() . '.'.$file->clientExtension();
$file->move( $destinationPath, $fileName );
$image = new Image;
$image->title = $fileName;
$image->article_id = $article->id;
$image->save();
}
public function store(Request $request){
$product = new product;
if($request->hasfile('image'))
{
$file = $request->file('image');
$exten = $file->getClientOriginalExtension();
$filename = time().".".$exten;
$file->move('uploads/product',$filename);
$product->image = $filename;
}
$product->save();
I have 2 public function in My Controller
public function index()
{
$projects = Project::personal()->get();
return view('projects.index')->withProject($projects);
}
other one is
public function show($id) {
$project = Project::find($id);
$tasks = $this->getTasks($id);
$files = $this->getFiles($id);
$comments = $this->getComments($id);
$collaborators = $this->getCollaborators($id);
return view('projects.show')->withProject($project)->withTasks($tasks)->withFiles($files)->withComments($comments)->withCollaborators($collaborators);}
I need get
$collaborators = $this->getCollaborators($id);
to My public function index() method to print collaborators in ('projects.index') view
how can do this?
Update your index function with this code, haven't tested it
public function index()
{
$projects = Project::personal()->get();
foreach($projects as $key => $project) {
$find = Project::find($project->id);
$tasks = $this->getTasks($project->id);
$files = $this->getFiles($project->id);
$comments = $this->getComments($project->id);
$collaborators = $this->getCollaborators($project->id);
$projects[$key]['collaborators'] = $collaborators;
}
return view('projects.index')->withProject($projects);
}
In ('projects.index') you will have collaborators value for each database record
I am building a project where Users kan upload Projects and other Users can comment on eachothers Projects
Now I was able to upload Projects and build a commenting system but now I am no longer able to upload projects I am only able to comment on projects that were already stored in my db.
Someone knows why I am no longer able to store Projects?
My routes:
// add comment
Route::post('projects/{id}','CommentController#store');
//Project routes REST methode
Route::post('projects/store', 'ProjectsController#store');
Route::resource('projects', 'ProjectsController');
My ProjectsController:
public function index()
{
$projects = Project::all();
//return $projects;
return view('projects.index', compact('projects'));
}
public function create()
{
return view('projects.create');
}
public function store(Request $request)
{
// getting all of the post data
$file = array('image' => Input::file('image'));
// setting up rules
$rules = array('image' => 'required',); //mimes:jpeg,bmp,png and for max size max:10000
// doing the validation, passing post data, rules and the messages
$validator = Validator::make($file, $rules);
if ($validator->fails())
{
// send back to the page with the input data and errors
return Redirect::to('projects/create')->withInput()->withErrors($validator);
}
else
{
// checking file is valid.
if (Input::file('image')->isValid())
{
$destinationPath = 'uploads/projects'; // upload path
$extension = Input::file('image')->getClientOriginalExtension(); // getting image extension
$fileName = rand(11111,99999).'.'.$extension; // renameing image
Input::file('image')->move($destinationPath, $fileName); // uploading file to given path
// sending back with message
Session::flash('success', 'Upload successfully');
}
else
{
// sending back with error message.
Session::flash('error', 'uploaded file is not valid');
return Redirect::to('projects/create');
}
}
$input = Request::all();
$project = new Project;
$project->user_id = Auth::id();
$project->title = $input['title'];
//$project->tags = $input['tags'];
$project->summary = $input['summary'];
$project->file_name = $fileName;
$project->published_at = Carbon::now();
$project->save();
return Redirect::to('projects');
}
public function show($id)
{
$input = Request::all();
$project = Project::all()->load("User");
//$project_comments = Comment::where('on_projects', '=', $id)->join('users', 'users.id', '=', 'comments.from_user')->get();
$project_comments = DB::table('comments')
->select('body', 'name')
->where('on_projects', '=', $id)
->join('users', 'users.id', '=', 'comments.from_user')
->get();
return view('projects.show', ['project' => Project::findOrFail($id), 'comments' => $project_comments]);
}
My CommentController
public function store()
{
$input = Request::all();
$comment = new Comment;
$comment->body = $input['body'];
$comment->on_projects = $input['project_id'];
$comment->from_user = Auth::user()->id;
$comment->save();
return redirect('projects/'.$input['project_id']);
}
My Project model
class Project extends Model
{
protected $fillable = [
'user_id',
'title',
//'tags',
'summary',
'file_name',
'published_at'
];
public function User()
{
return $this->belongsTo('App\User');
}
/**
* Haal de tags op die gerelateerd zijn aan desbetreffende project
*/
public function tags()
{
return $this->belongsToMany('App\Tag')->withTimestamps();
}
}
My Comment model:
class Comment extends Model
{
//comments table in database
protected $guarded = [];
protected $table = 'comments';
public function user()
{
return $this->belongsTo('App\User');
}
// returns post of any comment
public function post()
{
return $this->belongsTo('App\Project','project_id');
}
public $timestamps = false;
}
I fixed it by re-arranging my routes like this
//Project routes REST methode
Route::post('projects/store', 'ProjectsController#store');
Route::resource('projects', 'ProjectsController');
// add comment
Route::post('projects/{id}','CommentController#store');