I have two tables Cars and Features, where Cars and Features have one to many relations.
Cars table has ID, Name columns. Features tables has ID, CarID, Name, Feat Image.
When I update the details, Cars table updated Features table is not updated.
Cars.php
public function features() {
return $this->hasMany(Features::class, 'cars_id');
}
Features.php
public function feat()
{
return $this->belongsTo(Cars::class, 'cars_id');
}
Controller.php
Update Method
public function update(Request $request, $id)
{
$requestData = $request->all();
$cars = Cars::findOrFail($id);
$features = Features::with(['feat'])->where('cars_id', $cars->id)->get();
if($cars->update($requestData))
{
if ($request->hasFile('feat_img'))
{
$file = $request->file('feat_img');
$rules = array('file' => 'required|mimes:png,gif,jpeg');
$validator = \Illuminate\Support\Facades\Validator::make(array('file'=> $file), $rules);
if($validator->passes())
{
$name = $request->name;
for ($i=0; $i < count(request('name')); ++$i)
{
$features->name = request('name')[$i];
$feat_img_name = uniqid() . '.' . $images[$i]->getClientOriginalExtension();
$images[$i]->move(public_path('/images/'), $feat_img_name);
$features->feat_img = '/images/'.$feat_img_name;
}
}
}
$cars->features()->update($features);
session()->flash('message', 'Product updated successfully.');
return redirect('/');
}
Store Method
public function store(Request $request, Cars $cars)
{
$cars= new Cars;
$cars->name= request('name');
$cars->image= $image;
if($cars->save())
{
$features= [];
$images = $request->file('feat_img');
$name = $request->name;
for ($i=0; $i < count(request('name')); ++$i)
{
$features= new Features;
$features->name = request('name')[$i];
$feat_img_name = uniqid() . '.' . $images[$i]->getClientOriginalExtension();
$images[$i]->move(public_path('/images/'), $feat_img_name);
$features->feat_img = '/images/'.$feat_img_name;
$cars->features()->save($features);
}
session()->flash('message','Product successfully added.');
return redirect ('/');
}
}
Use update like this :
$features=Features::findOrFail(id);
$features->field=$value;
$features->save();
Hope this works.
Related
I am building a blog using Laravel 9 and my update method for some unknown reason fails to update
My code Samples
Model
class Anime extends Model
{
use HasFactory;
protected $table = 'anime';
protected $primaryKey = 'id';
protected $fillable = ['anime_title','user_id','blog_title','description','slug','anime_image_profile'];
public function blogInformation() {
return $this->hasMany(BlogInfo::class);
}
public function getRouteKeyName()
{
return 'slug';
}
// protected $hidden = 'id';
}
Controller
public function update(ValidateAnimeBlogRequest $request, $id)
{
$request->validated();
/*Update the details in the database by ID*/
$update_data = Anime::findOrFail($id);
$update_data = new Anime;
$update_data->anime_title = $request->input('anime_title');
$update_data->blog_title = $request->input('blog_title');
$update_data->user_id = auth()->user()->id;
$update_data->description = $request->input('description');
$update_data->slug = Str::slug($request->input('blog_title'));
/*Check if the user also wanted to update the image*/
if($request->hasFile('anime_image_profile')) {
$path_to_images = 'images/anime_image_profile/' . $update_data->anime_image_profile;
if(File::exists($path_to_images)) {
File::delete($path_to_images);
}
$new_file_name = '9anime' . '-' . time() . '-' . $request->name . '.' . $request->anime_image_profile->extension();
$request->anime_image_profile->move(public_path('images/anime_image_profile'), $new_file_name);
$update_data->anime_image_profile = $new_file_name;
}
if($update_data->update()) {
redirect('/');
}
dd('Error');
}
ValidateAnimeBlogRequest
public function rules()
{
return [
'anime_title' => 'required | min:2', new nameRegex,
'blog_title' => ['required','min:5', new nameRegex],
'description' => ['required','min:1000'],
'premiered' => ['required'],
'genre' => ['required', new nameRegex],
'licensors' => ['required', new nameRegex],
'studio' => ['required', new nameRegex],
'anime_image_profile' => 'required | mimes:jpeg,jpg,png | max:5408'
];
}
My blade file
<form enctype="multipart/form-data" autocomplete="off" action="/blog/{{$anime['id']}}" method="POST">
#method('PUT')
#csrf
I set up a custom check just in case
if($update_data->update()) {
redirect('/');
}
dd('Error');
The output on my webpage from this is "Error" // app\Http\Controllers\AnimeController.php:156
And when I dd($update_data) I see that the data has been updated yet it does not get sent to the database.
I tried replacing $update_data->update() with $update_data->save() but that now creates new data in the DB instead of updating the existing one
You can keep it as the save() method. Just update the lines above where you are creating a new Anime() instance to only be created if the record cannot be found via $id from the line above.
public function update(ValidateAnimeBlogRequest $request, $id)
{
$request->validated();
/*Update the details in the database by ID*/
$update_data = Anime::findOrFail($id);
if(!$update_data) {
$update_data = new Anime;
}
$update_data->anime_title = $request->input('anime_title');
$update_data->blog_title = $request->input('blog_title');
$update_data->user_id = auth()->user()->id;
$update_data->description = $request->input('description');
$update_data->slug = Str::slug($request->input('blog_title'));
/*Check if the user also wanted to update the image*/
if($request->hasFile('anime_image_profile')) {
$path_to_images = 'images/anime_image_profile/' . $update_data->anime_image_profile;
if(File::exists($path_to_images)) {
File::delete($path_to_images);
}
$new_file_name = '9anime' . '-' . time() . '-' . $request->name . '.' . $request->anime_image_profile->extension();
$request->anime_image_profile->move(public_path('images/anime_image_profile'), $new_file_name);
$update_data->anime_image_profile = $new_file_name;
}
if($update_data->save()) {
redirect('/');
}
dd('Error');
}
This will create a new instance only if a record is not found and won't give a new db record
this Is the Model which I am using for inserting photos in Photos Table by use of MorphMany Realtions in laravel in Object Model
public function photos(){ return $this->morphMany('App\Photo', 'photoable');}
photable function in Photo model
public function photoable(){
return $this->morphTo();
}
form for adding photos.
<input type="file" name="objectPictures[]" id="objectPictures" multiple><br>
here I am inserting the Object in objects table along with Photos in Photos table. Object inserted successfully but photos are not inserting.
public function saveObjectby(Request $request)
{
$inputs=request()->validate([
'name'=> 'required|min:8|max:255',
'description'=> 'required',
]);
$object = new TouristObject();
$object->user_id = $request->user()->id;
$object->name = $request->input('name');
$object->package_id = $request->input('package_id');
$object->description = $request->input('description');
$object->save($inputs);
if ($request->hasFile('objectPictures'))
{
$this->validate($request, \App\Photo::imageRules($request,'objectPictures'));
foreach($request->file('objectPictures') as $picture)
{
$path = $picture->store('objects', 'public');
$photo = new Photo;
$photo->path = $path;
$object->photos()->save($photo);
}
}
}
I'm trying to save multiple images of my property, a property can have several images, but I get this error
I would like to know what it produces if you can help me here I leave my controller in the store function
code upload image
public function store(Request $request)
{
/*--from this session you start to save the properties with all their attributes --*/
$properti = new Propertie;
$detail = new Detail;
$detail->antiquity = $request->antiquity;
$detail->furnished = $request->furnished;
$detail->floor = $request->floor;
$detail->save();
$properti->details_id = $detail->id;
$properti->name = $request->name;
$properti->price = $request->price;
$properti->description = $request->description;
$properti->departaments_id = $request->departaments;
$properti->municipalities_id = $request->municipalities;
$properti->property_type_id = $request->type_property;
$properti->offer_type_id = $request->type;
$properti->details_id = $detail->id;
$properti->images = $request->images;
$properti->lat = $request->lat;
$properti->lng = $request->lng;
$properti->address = $request->address;
if (isset($request->property_id)) {
$property_type = $request->property_id;
} else {
$property_type = null;
}
$images=array();
if($files=$request->file('images')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move('image',$name);
$images[]=$name;
}
}
$properti->save();
$piso_id = $properti->id;
$space = new Space;
$space->property_id = $piso_id;
$space->bedrooms = $request->bedrooms;
$space->bathrooms = $request->bathrooms;
$space->parking = $request->parking;
$space->area = $request->area;
$space->save();
$properti->spaces_id = $space->id;
foreach ($request->input('characteristic') as $characteristic) {
$charc = new Characteristic;
$charc->property_id = $piso_id;
$charc->characteristic = $characteristic;
$charc->save();
}
Session::flash('message', 'Se ha registrado su propiedad De forma exitosa');
return redirect()->action('PropertyController#index');
// return view('properties.index',compact('properties'));
}
Migration - Properties
public function up()
{
Schema::create('properties', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable;
$table->string('price')->nullable;
$table->text('description')->nullable;
$table->unsignedBigInteger('property_type_id')->nullable();
$table->unsignedBigInteger('offer_type_id')->nullable();
$table->unsignedBigInteger('spaces_id')->nullable();
$table->unsignedBigInteger('departaments_id')->nullable();
$table->unsignedBigInteger('municipalities_id')->nullable();
$table->unsignedBigInteger('details_id')->nullable();
//$table->unsignedBigInteger('characteristics_id')->nullable();
$table->unsignedBigInteger('images_id')->nullable();
$table->decimal('lat', 8, 5)->nullable;
$table->decimal('lng', 8, 5)->nullable;
$table->string('address')->nullable;
$table->timestamps();
$table->foreign('property_type_id')->references('id')->on('property_type');
$table->foreign('offer_type_id')->references('id')->on('offer_type');
$table->foreign('spaces_id')->references('id')->on('spaces');
$table->foreign('departaments_id')->references('id')->on('departaments');
$table->foreign('municipalities_id')->references('id')->on('municipalities');
$table->foreign('details_id')->references('id')->on('details');
$table->foreign('images_id')->references('id')->on('images');
//$table->foreign('characteristics_id')->references('id')->on('characteristics')->onDelete('cascade');
});
}
Migration images
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->unsignedBigInteger('property_id');
$table->timestamps();
});
}
my property model
public function Images()
{
return $this->hasMany('App\Image', 'images_id');
}
model images
class Image extends Model
{
protected $fillable = ['name', 'property_id'];
public function properties()
{
return $this->belongsTo('App\Properties');
}
}
I don't know if I have something wrong with my controller but it gives me the error before saving it
This is assigning an array to images:
$properti->images = $request->images;
You are then calling $properti->save() which is trying to save that array, which it can't; it will try to convert it to a string, which it can't. So you can comment/remove this line.
If you want to save these via the relationship you can try something like this:
$properti->save();
foreach($files as $file) {
$name=$file->getClientOriginalName();
$file->move('image',$name);
// create a new Image and relate it to the property
$properti->images()->create(['name' => $name]);
}
I have a form with two pivot tables. One of them works just fine but I can't seem to be making the second one work despite them being quite similar. The one not working is for an image table called 'photos' and the form upload in called 'releases'. I called the pivot table 'photo_releases' with the 'photo_id' and a 'release_id' field.
DB Pivot Table
here is the release Modal
class Release extends Model
{
public function photos()
{
return $this->belongsToMany('App\Photo', 'photo_releases', 'release_id', 'photo_id');
}
}
and the photo modal
class Photo extends Model
{
public function releases()
{
return $this->belongsToMany('App\Release', 'photo_releases', 'photo_id', 'release_id');
}
}
and the ReleaseController
public function store(ReleasesCreateRequest $request)
{
$input = $request->all();
$user = Auth::user();
if ($file = $request->file('photo_01')) {
$file_name = preg_replace("/[^a-zA-Z0-9.]/", "", $file->getClientOriginalName());
$name = time() . 'photo_01' . $file_name;
$file->move('images', $name);
$input['photo_01'] = $name;
$photo = new Photo();
$photo->url = $input['photo_01'];
$photo->save();
}
$release = Release::create($request->except('release_id'));
dd($request->except('release_id'), $request->get('photo_id', []), $request->get('artiste_id', []));
$release->photos()->attach($request->get('photo_id', []));
$release->artistes()->attach($request->get('artiste_id', []));
return redirect('/admin06000/releases');
}
There is two pivot tables being used in this function. the one using
"$release->artistes()->attach($request->get('artiste_id', []));"
is working correctly but the photos is not. The url is being logged in the correct DB and the image is uploading fine, but the pivot table is not being updated. If anyone could help it would be greatly appriciated.
try This if you need some select in relation ship change
with('photos')
to
with(['photos'=>function($query){$query->where(....)->get();}])...
use Image;
use Illuminate\Support\Facades\Input;
...
public function store(ReleasesCreateRequest $request)
{
$input = $request->all();
$user = Auth::user();
if ($file = $request->file('photo_01'))
{
$image= Input::file('photo_01');
$name = time().'photo_01'.'.'.$image->getClientOriginalExtension();
$path=public_path('/YourPath/'.$name);
Image::make($image->getRealPath())->save($path);
$photo = new Photo();
$photo->url = '/YourPath/'.$name;
$photo->save();
}
$release = Release::create
([
'release_field'=>$amount,
'release_field2'=>$amount2,
....
]);
$release->with('photos')->with(artistes)->get();
}```
I have many to many relationships between posts and tags
The problem is when I want to get the post id and the tag id to link them in their immediary table I did a simple query to do that and I used latest() method in laravel query builder and it threw this error:
Method Illuminate\Support\Collection::latest does not exist.
This is my store function:
public function store(Request $request)
{
{
$this->validate($request,[
'title'=>'required',
'body'=>'required',
'tags'=>'required',
'slug'=>'required',
]);
$input = $request->all();
$tags = explode(",", $request->tags);
if ($input != null) {
$post = post::create($input);
$post->tag($tags);
// the problem is in this two lines
$post_id = DB::table('posts')->pluck('id')->latest();
$tagged_id = DB::table('tagging_tagged')->pluck('id')->latest();
//
dd($tagged_id , $post_id);
$relationship = new post_tagged;
$relationship->post_id = $post_id;
$relationship->tagged_id = $tagged_id;
$relationship->save();
return redirect('/admin/blog')->with('success' , 'Post added successfully');
}
return redirect('/admin/blog');
}
}
the idea that I want to achieve with those two lines is to get the latest id in the post table and in the tags table (which is the newest post)
and then storing it in the immediary table
I solved the problem by doing this
store function
public function store(Request $request)
{
{
$this->validate($request,[
'title'=>'required',
'body'=>'required',
'tags'=>'required',
'slug'=>'required',
]);
$input = $request->all();
$tags = explode(",", $request->tags);
if ($input != null) {
$post = post::create($input);
$post->tag($tags);
$post_id = DB::table('tagging_tagged')->latest('taggable_id')->first();
$post_id = $post_id->taggable_id;
$tagged_id = DB::table('tagging_tagged')->latest('id')->first();
$tagged_id = $tagged_id->id;
$relationship = new post_tagged;
$relationship->post_id = $post_id;
$relationship->tagged_id = $tagged_id;
$relationship->save();
return redirect('/admin/blog')->with('success' , 'Post added successfully');
}
return redirect('/admin/blog');
}