Array to string conversion Laravel upload multiples images - php

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

Related

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'DescAnunUser' cannot be null

I'm working with Laravel on my school project (beginner in programming), and I have an error that I don't know how to solve.
So when I try to add/update something in my table, the following error occurs:
Insomnia POST
the table, model and controller are as follows:
Schema::create('TblAnunUsuario', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id('idAnunUser');
$table->string('TituloAnunUser');
$table->string('DescAnunUser');
$table->integer('PrecoAnunUser');
$table->string('RequisitosAnunUser');
$table->string('ImgAnunUser');
$table->char('StatusAnunUser', 1);
$table->dateTime('DataAnunUser');
$table->unsignedBigInteger('idUserAnunUser')->unsigned();
$table->foreign('idUserAnunUser')->references('idUser')->on('TblUsuario');
$table->unsignedBigInteger('idTipoServAnunUser')->unsigned();
$table->foreign('idTipoServAnunUser')->references('idTipoServ')->on('TblTipoServico');
use HasFactory;
public $timestamps = false;
protected $primaryKey = 'idAnunUser';
protected $table = 'TblAnunUsuario';
protected $fillable = ['TituloAnunUser', 'DescAnunUser', 'PrecoAnunUser', 'RequisitosAnunUser','ImgAnunUser', 'StatusAnunUser', 'DataAnunUser', 'idUserAnunUser', 'idTipoServAnunUser'];
public function addAnunUsuario(Request $request)
{
$anunuser = New TblAnunUsuario();
$anunuser->TituloAnunUser = $request->TituloAnunUser;
$anunuser->DescAnunUser = $request->DescAnunUser;
$anunuser->PrecoAnunUser = $request->PrecoAnunUser;
$anunuser->RequisitosAnunUser = $request->RequisitosAnunUser;
$anunuser->ImgAnunUser = $request->ImgAnunUser;
$anunuser->StatusAnunUser = $request->StatusAnunUser;
$anunuser->DataAnunUser = $request->DataAnunUser;
$anunuser->idUserAnunUser = $request->idUserAnunUser;
$anunuser->idTipoServAnunUser = $request->idTipoServAnunUser;
$result = $anunuser->save();
if($result)
{
return response()->json([
'status'=>'200',
'message'=>'Anúncio inserido com sucesso',
]);
} else {
return response()->json([
'status'=>'400',
'message'=>'Falha ao inserir o anúncio',
]);
}
}
first option you have : $table->string('DescAnunUser')->nullable(); and run migration again
And second option you have:
public function addAnunUsuario(Request $request)
{ $request->validate([
'DescAnunUser' => 'required'
]);
$anunuser = New TblAnunUsuario();
$anunuser->TituloAnunUser = $request->TituloAnunUser;
$anunuser->DescAnunUser = $request->DescAnunUser;
$anunuser->PrecoAnunUser = $request->PrecoAnunUser;
$anunuser->RequisitosAnunUser = $request->RequisitosAnunUser;
$anunuser->ImgAnunUser = $request->ImgAnunUser;
$anunuser->StatusAnunUser = $request->StatusAnunUser;
$anunuser->DataAnunUser = $request->DataAnunUser;
$anunuser->idUserAnunUser = $request->idUserAnunUser;
$anunuser->idTipoServAnunUser = $request->idTipoServAnunUser;
$result = $anunuser->save();
if($result)
{
return response()->json([
'status'=>'200',
'message'=>'Anúncio inserido com sucesso',
]);
} else {
return response()->json([
'status'=>'400',
'message'=>'Falha ao inserir o anúncio',
]);
}
}

Laravel Create a new table entry while updating a column in another table

I am trying to create a new record in one table while updating a specific column in another table. One table is users, the other table is assigned_units.
This is the AssignedUnitController for store
public function store(AssignUnitRequest $request)
{
if ($request->isMethod('POST')) {
$data = $request->all();
//validate data
$validated = $request->validated();
$data['tenant_id'] = $request->get('tenant_id');
$data['prop_id'] = $request->get('prop_id');
$data['unit_id'] = $request->get('unit_id');
$data['billing'] = $request->get('billing');
$datetime = Carbon::createFromFormat('d/m/Y',$data['start_date']);
$data['start_date'] = $datetime;
AssignedUnit::create(
$data
);
if ($validated = $request->validated()) {
Session::flash('success', 'Unit is successfully assigned');
return redirect()->route('admin.tenants.index');
}
else {
return back();
Session::flash('error_message', 'Unit is not assigned');
}
}
}
This is the assigned controller for create
$data['tenant'] = User::findOrFail($id);
$data['properties'] = Property::getAllProperties();
$data['property'] = null;
$data['units'] = [];
$data['unit'] = null;
$data['rentings'] = AppHelper::RENTING_STATUS;
$data['renting'] = 1;
$data['cycles'] = AppHelper::BILLING_CYCLE;
$data['cycle'] = 1;
return view('admin.tenants.assign.form',$data);
I have a request $data['renting'] = $request->get('renting'); which is entered in this form but should be updated on the users table
the users table
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->enum('renting',[0,1]);
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
How do I update the users table, renting column, from AssignedUnitController

Having a problem with a pivot table on Laravel

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

Laravel - Update dynamic fields in relationship table

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.

trying to write Policy for enabling comment of posts in Laravel

In laravel I have a Follower table that I use to check if a User is folowing another User and also if he can comment on Posts.
The table is like this:
Schema::create('followers', function (Blueprint $table) {
$table->unsignedInteger('publisher_id')->unsigned();
$table->unsignedInteger('follower_id')->unsigned();
$table->boolean('enable_follow')->default('1');
$table->unique(['publisher_id', 'follower_id']);
$table->timestamps();
$table->foreign('publisher_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('follower_id')
->references('id')
->on('users')
->onDelete('cascade');
});
and these are the checks that I make to decide if a User can comment a Post:
public function canComment(User $user, Post $post)
{
$following = Follower::where('follower_id', $user->id)->where('publisher_id', $post->user_id)->select('enable_follow')->get();
if (!$following->isEmpty()) {
$enabled = $following[0]['enable_follow'];
if ($enabled != '0') {
return true;
} else {
return false;
}
} else if ($following->isEmpty()) {
return true;
}
}
And this is the controller part for storing, as You can see I'm trying to authorize like this: $this->authorize('canComment', $post[0]);
public function store(Request $request)
{
//on_post, from_user, body
// define rules
$rules = array(
'post_id' => 'required',
'body' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
$post_id = $request->input('post_id');
$post = Post::findOrFail($post_id);
if ($validator->fails()) {
return Response()->json($validator);
} else {
$this->authorize('canComment', $post);
//prepares object to be stored in DB
$comment = new Comment();
$comment['user_id'] = $request->user()->id;
$comment['post_id'] = $post_id;
$comment['body'] = $request->input('body');
$comment->save();
if ($comment) {
$comment['user_name'] = $request->user()->username;
$comment['comment_id'] = $comment->id;
$comment['token'] = $request->input('_token');
}
return Response()->json($comment);
}
}
The problem here is I get a 403 (Forbidden) error in a situation where I have $following empty and where following is enabled. The Policy is not working as expected.
Source code for authorize method in Gate facade:
public function authorize($ability, $arguments = [])
{
$result = $this->raw($ability, $arguments);
if ($result instanceof Response) {
return $result;
}
return $result ? $this->allow() : $this->deny();
}
Maybe I am not correct returing true or false in the policy as this code expect the result to be an instance of Response but so what do you return to grant or deny access??
The problem was putting the policy inside commentPolicy and so it expected to receive a Comment not a Post, moving it to postPolicy solved it.

Categories