Posting value to database laravel - php

I'm trying to add a description to my thumbnail but it won't update in my database.
Can you guys see why?
The only thumb_description won't update.
Fillables are filled. When i did $content->save() it will return true.
Controller:
public function detail(Request $request, $id)
{
$content = Content_blocks::find($id);
if ($request->isMethod('post')) {
if ($request->hasFile('image')) {
$folder = 'uploads';
$name = $request->image->getClientOriginalName();
$store = $request->image->store($folder, 'public');
$file = pathinfo(Storage::url($store));
$thumb_description = $request->input('thumb_description');
$thumbnail = new Thumbnail();
$thumbnail->name = $file['filename'];
$thumbnail->extenstion = $file['extension'];
$thumbnail->path = $folder;
$thumbnail->thumb_description = $thumb_description;
$thumbnail->save();
$content->thumbnail_id = $thumbnail->id;
}
$content->title = $request->input('title');
$content->description = $request->input('description');
$content->link = $request->input('link');
$content->linkname = $request->input('linkname');
$content->order = $request->input('order');
$content->contentcategory_id = $request->input('categorie');
$content->thumbnail->thumb_description = $request->input('thumb_description');
if ($request->input('ontkoppel') === 'deletion') {
Thumbnail::find($content->thumbnail_id)->delete();
}
// dd($content->thumbnail->thumb_description);
$content->save();
return redirect('admin/content/webcategorie/homepage/contentblocks/' . $content->content_id);
}
Model
<?php
namespace App\Models;
use Illuminate\Support\Facades\Storage;
class Thumbnail extends Model
{
protected $fillable = [
"thumb_description",
"name",
"path",
"extenstion"
];
protected $table = 'thumbnail';
public function content()
{
return $this->belongsTo(Content::class);
}
public static function getFile($id)
{
$thumbnail = self::find($id);
if ($thumbnail === null) {
return null;
}
$url = sprintf('%s/%s.%s', $thumbnail->path, $thumbnail->name, $thumbnail->extenstion);
return Storage::disk('public')->url($url);
}
public static function getDescription($id)
{
$thumbnail = self::find($id);
if ($thumbnail === null) {
return null;
}
$description = $thumbnail->thumb_description;
return $description;
}
}
Migration
*/
public function up()
{
Schema::create('thumbnail', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 255);
$table->string('path', 150);
$table->string('extenstion', 10);
$table->text('thumb_description');
$table->timestamps();
});
}
Post in chrome dev tools
------WebKitFormBoundaryfun4SMk5TA604OZE
Content-Disposition: form-data; name="thumb_description"
bruyanga

$content->save(); will only save the attributes on $content and not its relationships.
Try $content->push(); instead which should cascade through the loaded relationships and save all related models as well.
https://laravel.com/api/5.6/Illuminate/Database/Eloquent/Model.html#method_push

Related

How to store imageable_id and imageable_type in photos table Laravel?

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(...)

Delete entrys in Database with foreignkey and pivot relations laravel 8

Hey im searching for a method to delete adn entry which is connected to some other with ManytoMany and belongstoMany Relations, my question is how can i get an query that it finds the relations and checks it, if there are none it should be deleted and if there are some it should not delete it.
this is my Controller:
public function index()
{
$tracks = Track::all();
$seasons = Season::all();
return view('index.track', compact('tracks', 'seasons'));
}
public function create(): \Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Contracts\Foundation\Application
{
$seasons = Season::all();
$topics = Topic::all();
$speakers = Speaker::all();
return view('create.track', compact('topics', 'seasons', 'speakers'));
}
public function store(TrackStore $request): \Illuminate\Http\RedirectResponse
{
$hashedName = Hash::make($request->file('track_data')->getClientOriginalName()) . "." . $request->file('track_data')->getClientOriginalExtension();
$request->track_data->storeAs('public/tracks', $hashedName);
$track = new Track();
$track->title = $request->track_title;
$track->description = $request->track_description;
$track->data = $hashedName;
$track->season_id = $request->season_id;
$track->save();
$track->speakers()->attach($request->input('speakers'));
$track->topics()->attach($request->input('topics'));
if($request->input('moderators')) {
$data = [];
foreach ($request->input('moderators') as $moderatorId) {
$data[$moderatorId] = ['is_moderator' => 1];
};
$track->speakers()->attach($data);
return redirect()->route('admin.trackShow');
} else {
return redirect()->route('admin.trackShow');
}
}
public function delete(Track $id): \Illuminate\Http\RedirectResponse
{
$id->delete();
return redirect()->route('admin.trackShow');
}
public function edit(Track $id)
{
return view('edit.track');
}
This is my Model:
class Track extends Model
{
use HasFactory;
protected $table = 'tracks';
protected $primaryKey = 'id';
protected $fillable = [
'title',
'description',
'data',
'season_id',
];
public function season(): BelongsTo
{
return $this->belongsTo(Season::class);
}
public function speakers(): BelongsToMany
{
return $this->belongsToMany(Speaker::class, 'speakers_tracks', 'track_id', 'speaker_id')->withPivot('is_moderator');
}
public function topics(): BelongsToMany
{
return $this->belongsToMany(Topic::class, 'topics_tracks', 'track_id', 'topic_id');
}
}
This is my migration:
Schema::create('tracks', function (Blueprint $table) {
$table->id('id');
$table->string('title');
$table->string('description');
$table->string('data');
$table->integer('season_id')->unsigned();
$table->timestamps();
$table->softDeletes();
});
As you see the Tracks are connected to many other stuff they are connected via relations. thanks in advance!
It will be easy with count()
if ($supplier->items()->count() == 0) $supplier->delete();
It is not your model. But you will get the idea.

Laravel: save image in database

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();

how to solve the problem of file does not exist in laravel

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

Laravel's Eloquent: can't edit values

I'm using Lumen, trying to edit values, which is the easiest thing to do, for some reason, the updated values aren't being saved
Task.php model
public function taskUsers()
{
return $this->hasMany('App\Models\Tasks\UserTask')->where('role',1);
}
UserTask.php model contains nothing, an empty model
class UserTask extends BaseModel { }
Migrations
class CreateTasksTable extends Migration
{
protected $table = 'tasks';
protected $app_table = true;
public function up()
{
Schema::create($this->getTable(), function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->dateTime('submit_date');
$table->dateTime('closed_date')->nullable();
$table->dateTime('due_date')->nullable();
$table->tinyInteger('is_done')->nullable()->default(0);
$table->integer('domain_id')->unsigned()->nullable();
$table->foreign('domain_id')->references('id')
->on(self::getTableName('domains'))->onDelete('cascade');
$table->bigInteger('created_by')->unsigned()->nullable();
$table->foreign('created_by')->references('id')
->on(self::getTableName('auth_users', false))->onDelete('cascade');
$table->bigInteger('closed_by')->unsigned()->nullable();
$table->foreign('closed_by')->references('id')
->on(self::getTableName('auth_users', false))->onDelete('cascade');
$table->timestamps();
});
}
public function down()
{
Schema::drop($this->getTable());
}
}
and
class CreateTaskUsersTable extends Migration
{
protected $table = 'task_user';
protected $app_table = true;
public function up()
{
Schema::create($this->getTable(), function (Blueprint $table) {
$table->increments('id');
$table->integer('task_id')->unsigned()->nullable();
$table->foreign('task_id')->references('id')
->on(self::getTableName('tasks'))
->onDelete('cascade');
$table->bigInteger('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')
->on(self::getTableName('auth_users', false))
->onDelete('cascade');
$table->integer('role');
});
}
public function down()
{
Schema::drop($this->getTable());
}
}
The edit action for example is so simple, if I just want to edit the title, that won't work, without even editing the rest.
class EditTaskAction extends BaseAction
{
protected $verbs = array('POST');
protected $private = true;
protected $inputRules = [
'domain_id' => 'required',
'task_id' => 'required',
'title' => '',
'due_date' => '',
'assignee_id' => '',
'is_done' => '',
'role' => ''
];
public function execute()
{
$title = $this->request->get('title');
$dueDate = $this->request->get('due_date');
$assigneeId = $this->request->get('assignee_id');
$taskId = $this->request->get('task_id');
$isDone = $this->request->get('is_done');
$role = $this->request->get('role');
$userId = \Auth::id();
$domainId = $this->request->get('domain_id');
\DB::beginTransaction();
try {
$task = Task::where('id', $taskId)
->where("domain_id", $domainId) ->first();
$userTask = UserTask::where('task_id', $taskId)->first();
if (isset($title) && !empty($title)) {
$task->title = $title;
}
if (isset($dueDate) && !empty($dueDate)) {
$task->due_date = $dueDate;
}
if (isset($assigneeId) && !empty($assigneeId)) {
$userTask->user_id = $userId;
}
if (isset($role) && !empty($role)) {
if ($role == TaskUserRole::ASSIGNEE) {
$userTask->role = $role;
}
}
if (isset($isDone) && !empty($isDone) ) {
if ($isDone == 0) {
$task->closed_by = null;
$task->closed_date = null;
$task->is_done = 0;
} else if ($isDone == 1) {
$task->closed_by = $userId;
$task->closed_date = Carbon::now();
$task->is_done = 1;
}
}
$task->save();
$userTask->save();
return $this->response->statusOk();
} catch (\Exception $exception) {
\DB::rollBack();
\Log::error($exception);
$this->response->addErrorDialog(self::SOMETHING_WENT_WRONG);
return $this->response->statusFail(self::SOMETHING_WENT_WRONG);
}
\DB::commit();
}
}
Basically all I'm doing
$task = Task::find($taskId); // I tried that too
$task->title = 'something';
$task->save();
It's not working
I think the problem is with your transaction. You're starting it with \DB::beginTransaction(); But the \DB::commit() (to save your changes to the database) will never be run, because you do Return-Statements before, like return $this->response->statusOk();
You could try to save your response to a variable and return it after the \DB::commit();
class EditTaskAction extends BaseAction
{
// ...
public function execute()
{
// ...
$response = null;
\DB::beginTransaction();
try {
// ...
$task->save();
$userTask->save();
$response = $this->response->statusOk();
} catch (\Exception $exception) {
// ...
$response = $this->response->statusFail(self::SOMETHING_WENT_WRONG);
}
\DB::commit();
return $response;
}
}
i thinks the problem in your model do you put your data stored in fillable
Did you set the guarded property on the model? You can completely disable guarding by setting it to an empty array.
protected $guarded = [];
// or check this:
protected $fillable = [...];
Otherwise you might find some error in the logs.

Categories