Default value for a photo in laravel - php

Hi i'm trying to make a function that allows everyone to publish whatever they want but when the visitor is not a user his post photo's default will be a photo from my directory storage that holds the meaning of anonymous or something alike:
what is the SQL command line that allows me to do so?
My post migration table is:
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('username');
$table->string('body');
$table->boolean('valid')->default(0);
$table->string('photo',150)->nullable();
$table->timestamps();
});
My function store() is the following:
public function store(Request $request)
{
$post= new Post();
$post->title=$request->input('title');
$post->photo=$request->photo; //what do i change in this field?
$post->username=$request->input('username');
$post->body=$request->input('body');
$post->save();
return redirect ('/ed');
}
Any ideas would be appreciated, thank you

You can use this:
use Illuminate\Support\Facades\Auth;
if (Auth::check()) {
// The user is logged in...
$postPhoto = $request->photo
} else{
//photo from directory storage
$postPhoto = public_path('/images/default.jpg');
}
// store photo in the database
$post->photo = $postPhoto;

#Wellwisher is right! But you can also set a default value to the photo field at posts table (and that is if you not planning to change the image name).
$table->string('photo', 150)->default('avatar.jpg');
and you will overwrite (change) it in case user uploads a new image as his/her profile image.

Related

function static::created does not save properly Laravel

So I have 2 tables: Item and Product. An Item hasMany Products and a Product belongsTo an Item.
Products migration:
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('hashed_id')->nullable()->unique();
$table->bigInteger('item_id')->unsigned();
$table->bigInteger('user_id')->unsigned();
$table->integer('state')->default(1);
$table->decimal('price');
$table->string('slug')->nullable()->unique();
$table->timestamps();
$table->foreign('item_id')->references('id')->on('items')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
For the hashed_id I use the following package: https://packagist.org/packages/hashids/hashids to create a hashed id to show in the url.
Product.php
public static function boot()
{
parent::boot();
static::created(function ($product) {
$productId = $product->id;
$hashids = new Hashids("", 10, 'abcdefghijklmnopqrstuvwxyz1234567890');
$hashedId = $hashids->encode($productId++);
$slug = Str::slug($product->item->slug . '-' . $hashedId);
$product->hashed_id = $hashedId;
$product->slug = $slug;
});
}
ProductsController.php
public function createSelfProduct(Request $request)
{
$product = auth()->user()->products()->create([
'item_id' => $request->item_id,
'user_id' => auth()->user()->id,
'price' => $request->price,
]);
// create the product and show seller info
return new ProductResource($product->load('user'));
}
What I'm trying to do is that when a user creates a new product, it should get the slug from the item model, put the $hashedId behind it and save that to the db. Now, when I do a post request via Postman, I get the desired result, as hashed_id and slug are saved. But when I check the database, both hashed_id and slug are NULL. Only the item_id, user_id and price are saved. What am I doing wrong and how can I fix this?
The created event means the Model has already been created. This is not before save, but after it has been saved. If you alter anything at this point you will need to save the record again.
Simply: You forgot to call save on your model instance to save the changes after you altered it.
Laravel has a convenient way of handling this with Observers
https://laravel.com/docs/5.8/eloquent#observers
php artisan make:observer ProductObserver
Then in Observers/ProductObserver.php
public function created(Product $product) {
$product = ''; // whatver you need to do here. $product is an instance of Product model
// Dont forget to save your model after modifying
$product->save();
}

Vue.js Get public folder images in laravel 5.8

I am creating commenting system, now, I want to show user profile images in comment area.
I want to catch and show multiple images from laravel 5.8 public folder. Here is what I tried.
If user has a profile image, I want to show it. If not, I want to show
an avatar using vue avatar component. My images are stored in
public/uploads/profile.
Now I don't have any errors in my console. Also I can show user name and user comments.
Image name is stored in mysql.
comment.vue(first comment)
<div class="user" v-if="comment.user.image && comment.user.image.length > 0">
<span :v-for="(item, index) in comment.user.image">
<img :src="'uploads/' + 'profile' + '/' + item.image">
</span>
</div>
<div else class="user" >
<avatar :username="comment.user.name" :size="45"></avatar>
</div>
commentController.php
public function index(Post $post)
{
return $post->comments()->paginate(10);
}
public function show(Comment $comment)
{
return $comment->replies()->paginate(10);
}
public function store(Request $request, Post $post)
{
return auth()->user()->comments()->create([
'body' => $request->body,
'post_id' => $post->id,
'comment_id' => $request->comment_id
])->fresh();
}
profiles table
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('user_id');
$table->string('image');
$table->string('gender');
$table->string('country');
$table->string('bod');
$table->string('instagram');
$table->string('description');
$table->timestamps();
});
In my VS code, uploads folder started turning red.
My solution is create a api route to show image. For example.
api.php
Route::get('profile/{fileName}', 'ProfileController#showImage');
ProfileController.php
class ProfileController {
...
public function showImage($fileName)
{
$path = public_path("/images/{$fileName}");
if (!\File::exists($path)) {
return response()->json(['message' => 'Image not found.'], 404);
}
$file = \File::get($path);
$type = \File::mimeType($path);
$response = \Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
}
}
And you image src will be /api/profile/{imageName}. This is my solution.

How can i delete a file when a record is deleted from database ? (Laravel)

My database registration is
$cover = Storage::disk('public')->putFile('images', $file);
$article->cover = $cover;
$article->save();
Article table connected to another table with cascade, when the record is deleted, the article record is also deleted. The file path registered in article table, but it still stands in folder. How can i delete the file, is it possible ?
EDIT
Schema::create('articles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('blog_id')->nullable();
$table->timestamps();
$table->foreign('blog_id')
->references('id')
->on('blogs')
->onDelete('cascade');
});
When blog record is deleted, article record also deleted. So i cant any procces in controller.
You need something like this in your model:
public static function boot ()
{
parent::boot();
self::deleting(function ($file) {
Storage::disk('public')->delete('images/'.$file);
});

Issues with saving an image with an article

I'm pretty sure this is a noob question, even though I'm used to PHP, but not to Laravel
My goal can't be any more simple, I'd like to be able to write an article and add an image to it, but even though I made the upload system work (that wasn't a piece of cake), I'm having issues with saving the filename itself.
Here's how I proceeded:
use App\Photo;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
public function store(Request $request)
{
$file = $request->file('image');
$originalname = $file->getClientOriginalName();
$path = 'uploads/' . $originalname;
Image::make($file)->save($path);
$product = new Photo(array(
'name' => $request->get('name'),
'image' => $originalname
));
$product->save();
return \Redirect::route('photo.index', array($product->id))->with('message', 'Product added!');
}
And here is my migration file, if this can help:
public function up()
{
Schema::create('photos', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('image');
$table->timestamps();
});
}
So I wanted to save the filename as a string inside the database so I could call it later, like with $product->image, however I'm getting the following error:
SQLSTATE[HY000]: General error: 1364 Field 'image' doesn't have a default value (SQL: insert into `photos` (`name`, `updated_at`, `created_at`) values (sisdjfposd, 2017-05-31 22:42:18, 2017-05-31 22:42:18))
So I know what it means, and I don't like it because it was supposed to have a value: if I add die($originalname);before the line $product = new Photo array(, i get my filename so logically the variable isn't empty.
So why would I have this error? Am i missing something?
Thank you in advance
I think you have missed adding image fields into mass assignment.
In your Photo model just add:
protected $fillable = ['name', 'image'];
More info on mass assignment:
https://laravel.com/docs/5.4/eloquent#mass-assignment

Laravel 5.2 multilanguage with dimsav/laravel-translatable

I am using dimsav for multilanguage and I have this problem after doing step by step from the guid. (dimsav)
I have a Model Category:
use Illuminate\Database\Eloquent\Model;
use Dimsav\Translatable\Translatable;
class Category extends Model {
use Translatable;
public $translatedAttributes = ['name'];
}
A CategoryTranslation:
use Illuminate\Database\Eloquent\Model;
class CategoryTranslation extends Model {
public $timestamps = false;
}
And in Controller when I try to save this with a specific language I get an error. This is my controller:
$language = App::getLocale();
$user = Auth::user();
$category = new Category();
$category->translate('en')->name = Input::get('name'); //line 35
$category->save())
And error:
at HandleExceptions->handleError('2', 'Creating default object from
empty value',
'C:\workspace\applications\wamp\www\lutz-paletten\app\Http\Controllers\CategoryController.php',
'35', array('language' => 'en', 'user' => object(User), 'category' =>
object(Category))) in CategoryController.php line 35
PS: this is my migration:
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->integer('categoryId');
$table->integer('user_id');
$table->timestamps();
});
Schema::create('category_translations', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->string('name');
$table->string('locale')->index();
$table->unique(['category_id','locale']);
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});
What am I missing ?
If I use this, it works:
$category->name = Input::get('name');
And it will be saved with what is set as AppLocale but how can I use it with translate() ?
I don't know if you solved this or not, but i think you should check with a couple of things:
1- delete the Parentheses when initiating the Category object so it will become:
$category = new Category;
2- Change the extra Parentheses after the save function so it will be:
$category->save();
3- make sure your input is named correctly.
and that's all i can see, hope you solved already :).
BTW you don't need that
$table->integer('categoryId'); in your migration is not nessary since $table->increments('id); is playing that role!
happy coding :)
If you create a new record of Category, this last one saves record with your current Locale (default : en).
You just need to change $category->translate('en') by $category->getNewTranslation('en') or $category->translateOrNew('en') and it works !
For your example:
Create a category with default locale (config/app.php ==> locale => 'en'):
// CategoryController
public function createCategory(Request $request)
{
// Save record in *categories* table
// And save the default language (config/app.php ==> locale) in *category_translations* table.
$category = new Category::create($request);
}
Create a translation in an existing category:
public function createCategoryTranslation(Request $request, $id)
{
$category = Category::find($id)
// Solution 1 : If you want to explain the fields to be saved.
$category->getNewTranslation('en')->name = $request->input('name');
// Solution 2 : Mass assignement if you have multiple fields to be saved.
$category->getNewTranslation('en')->fill($request);
$category->save()
}
Update a translation:
public function updateCategoryTranslation(Request $request, $id)
{
$category = Category::find($id)
// Solution 1 : If you want to explain the fields to be saved.
$category->translate('en')->name = $request->input('name');
// Solution 2 : Mass assignement if you have multiple fields to be saved.
$category->translate('en')->fill($request);
$category->save()
}
CreateOrUpdate translation:
public function createOrUpdateCategoryTranslation(Request $request, $id)
{
$category = Category::find($id)
// Solution 1 : If you want to explain the fields to be saved.
$category->translateOrNew('en')->name = $request->input('name');
// Solution 2 : Mass assignement if you have multiple fields to be saved.
$category->translateOrNew('en')->fill($request);
$category->save()
}

Categories