I am currently new to laravel and I am working on a basic project where a service provider (SP) is able to post service details by filling up a form.
I am trying to check if SP has uploaded a featured image. If yes, then rename file by using
$featured = $request->featured;
$featured_new_name = time().$featured->getClientOriginalName();
$featured->move('uploads/services', $featured_new_name);
and saving it to the uploads/services/ directory.
My ServiceController.php looks like this
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'address' => 'required|max:255',
'city' => 'required|max:255',
'state' => 'required|max:255',
'zipcode' => 'required|integer|digits:5',
'category_id' => 'required',
'workingday' => 'required',
'content' => 'required'
]);
//checking if featured image (logo file) is uploaded or not
if($request->hasfile('featured'))
{
$featured = $request->featured;
$featured_new_name = time().$featured->getClientOriginalName();
$featured->move('uploads/services', $featured_new_name);
}
else { }
$featured->move('uploads/services', $featured_new_name);
$service = Service::create([
'name' => $request->name,
'content' => $request->content,
'address' => $request->address,
'city' => $request->city,
'state' => $request->state,
'zipcode' => $request->zipcode,
]);
if($request->hasfile('featured'))
{
$service = Service::create([
'name' => $request->name,
'content' => $request->content,
'featured' =>'uploads/services/'.$featured_new_name,
'address' => $request->address,
'city' => $request->city,
'state' => $request->state,
'zipcode' => $request->zipcode,
]);
}
$service->workingdays()->attach($request->workingday);
$service->categories()->attach($request->category_id);
$service->user_id=auth()->id();
$service->save();
Session::flash('success','Service created successfully');
return view('sp.services.create')->with('categories', Category::all())->with('workingday', Workingday::all());
}
In the migration file:
public function up()
{
Schema::create('services', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('address');
$table->string('city');
$table->string('state');
$table->string('zipcode');
$table->integer('routes_id');
$table->string('featured')->default('/uploads/services/default.png');
$table->text('content')->nullable();
$table->string('slug');
$table->integer('user_id');
$table->softDeletes();
$table->timestamps();
});
}
I am saving the logged in user_id along with all other service details.
When the user uploads a logo file, this code stores two records in the database: one with the correct user_id and one with 0. When the user does not upload the logo file, only one record is stored with all correct values.
Here user_id 2 is a correct entry. Please help me improve this code.
Seems your session expired, when you save the second record, that's why the user_id is 0 for your second record.
Can you check your session as follows before you save the record ?
if (Auth::user()) {
// post the data and save the record
} else {
// redirect the user to the login page
}
I think this portion of code help you to fix out the error.
class DocumentController extends Controller
{
public function store(Request $request)
{
$images = $request->file('files');
if($request->hasFile('files')) :
foreach ($images as $item):
$var = date_create();
$time = date_format($var, 'YmdHis');
$imageName = $time . '-' . $item->getClientOriginalName();
$item->move(base_path() . '/uploads/file/', $imageName);
$arr[] = $imageName;
endforeach;
$image = implode(",", $arr);
else:
$image = '';
endif;
DB::table('document')->insert(array('id' => $id,'image' => $image));
Session::flash('message', 'Image are uploaded successfully');
return redirect('/addimage');
}
}
Related
So i want to store Parent data and array child data at the same time in laravel 9 rest api, but i dont even know how to format the array store, i was tried some looping code and still cant. the relationship was one parent has many child. i want to store like this
this what i expect store value
the parent model it just have name & class, and the child model was foreign parent_id & name. the model
here my controller
public function store(Request $request){
$this->validate($request, [
'parent_name' => 'required',
'class' => 'required',
'child.*' => 'array',
]);
$child = $request->child;
$chd = [];
foreach($child as $cd){
array_push($chd, Child::create([
'child' => $cd,
]));
}
$this->updates->create($request->all());
return $this->index();
}
here the migration :
Schema::create('parent', function (Blueprint $table) {
$table->increments('id');
$table->string('parent_name');
$table->string('class');
$table->timestamps();
});
Schema::create('child', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('parent_id')->unsigned()->index();
$table->foreign('parent_id')->references('id')->on('parent_id')->onDelete('cascade');
$table->timestamps();
});
}
You may want to try this
public function store(Request $request) {
$rules = [
'parent_name' => 'required|string|max:255',
'class' => 'required|string|max:255',
'child' => 'required|array',
'child.name' => 'required|string|max:255',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return response()->json(['error' => true, 'error_msg' => 'invalid input']);
}
DB::beginTransaction();
$parent = Parent::create([
'parent_name' => $request->parent_name,
'class' => $request->class,
]);
foreach ($request->child AS $child) {
$child = Child::create([
'parent_id' => $parent->id,
'name' => $child['name'],
]);
}
DB::commit();
return response()->json(['error' => false]);
}
i have a product and i want it to have multiple file, so i made a oneToMany relation between product and images model.
i was able to upload image successfully
public function uploadFile(Request $request)
{
if($request->hasFile('images'))
{
foreach($request->file('images') as $file)
$file->store('public/images/'. $file->getClientOriginalName());
}
return $request->file('images');
}
now images are storage into storage/public/~ i want to them them to database
Here is my store function in ProductController
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'price' => 'required|numeric',
'description' => 'required',
'category' => 'required',
'attribute' => 'required',
'stocks' => 'required|numeric',
//'discounts' => 'required|numeric'
]);
$product = Product::create($request->only('name','price','description', 'tag', 'category', 'attribute'));
$product->stocks()->create([
'quantity' => $request->stocks,
'product_id' => $product->id
]);
$product->discounts()->create([
//'discount' => $request->discounts,
'product_id' => $product->id
]);
/*
foreach( $request->file('images') as $file)
{
$product->images()->create([
'product_id' => $product->id,
'file_path' => $file->hashName()
]);
}
*/
}
what should i add to it so i be able to store image into the table
update
images table schema
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('file_path');
$table->timestamps();
$table->foreignId('product_id')->constrained('products')->onUpdata('cascade')->onDelete('cascade');
});
product table schema
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->double('price');
$table->string('category');
$table->string('attribute');
$table->text('description');
$table->string('tag');
$table->timestamps();
});
You can do some think like below
$images=[];
foreach($request->file('images') as $file){
$fileName = time().Str::random(8).'.'.$file->getClientOriginalExtension();
$file->store('public/images/'.$fileName);
$images[]=['file_path'=>$fileName] ;
}
$product->images()->createMany($images);
I hope you have hasmany relationship in product model
I'm using Laravel 8 to develop my project and in this project, I have a page for adding new users and uploading their profile picture.
Now at the store() of Controller, I coded this:
public function store(Request $request)
{
$user = new User();
$validate_data = Validator::make(request()->all(),[
'name' => 'required|min:4',
'email' => 'required|email|unique:users',
'status' => 'required',
'role' => 'required',
'password' => 'required|min:6',
])->validated();
if($file = $request->file('avatar')){
$name = time() . $file->getClientOriginalName();
$file->move('images', $name);
$photo = new Photo();
$photo->name = $file->getClientOriginalName();
$photo->path = $name;
$photo->user_id = Auth::id();
$photo->save();
$user->photo_id = $photo->id; //Adding photo id to the new user at users table
}
$creation = User::create([
'name' => $validate_data['name'],
'email' => $validate_data['email'],
'status' => $validate_data['status'],
'role_id' => $validate_data['role'],
'password' => bcrypt($validate_data['password'])
]);
if($creation){
alert()->success('User was added', 'Success');
return redirect('/admin/users/');
} else {
return '1003';
}
}
It works fine and correct and adds the new user to users table and the photo to photos table.
But this line that should add the photo_id to users table, does not work and the photo_id of the new user is empty somehow!
And the relationship between User and Photo Models goes like this:
User.php:
public function photos()
{
return $this->hasMany(Photo::class);
}
Photo.php:
public function user()
{
return $this->belongsTo(User::class);
}
And I have also added photo_id as fillbale at User Model.
So what is going wrong here ? How can I fix this issue ?
I would really appreciate any idea or suggestion about this...
Thanks in advance.
Here are the Migrations, if you would like to see:
create_photos_table table:
public function up()
{
Schema::create('photos', function (Blueprint $table) {
$table->increments('id');
$table->string('path');
$table->string('name');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
add_avatar_to_users_table:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->integer('photo_id')->unsigned()->nullable();
});
}
In add_avatar_to_users_table migration change integer to bigInteger as follows:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->integer('photo_id')->unsigned()->nullable();
});
}
Remove the following line from code:
$user = new User();
Update the following chunk of code:
$creation = User::create([
'name' => $validate_data['name'],
'email' => $validate_data['email'],
'status' => $validate_data['status'],
'role_id' => $validate_data['role'],
'password' => bcrypt($validate_data['password']),
'photo_id' => isset($photo) ? $photo->id : null
]);
You need to save that model:
$user->save()
Otherwise the the change you made has no effect to the DB
There are 3 things:
If your users can have many photos then you won't need the photo_id on your users table, because all photos have a user_id, hence the one to many relationship
You define $user = new User() and assign the value to this object. But later you are creating an new User with this code:
$creation = User::create([
'name' => $validate_data['name'],
'email' => $validate_data['email'],
'status' => $validate_data['status'],
'role_id' => $validate_data['role'],
'password' => bcrypt($validate_data['password'])
]);
Therefore you have 2 User models and only one of them gets saved to the database.
And last, if you save the auth()->id() as the user_id of your photo the photo will not belong to the correct user. You will first have to create the user and then take this id.
some code of your store is wrong
at first you use
$user = new User();
after
$creation = User::create([
'name' => $validate_data['name'],
'email' => $validate_data['email'],
'status' => $validate_data['status'],
'role_id' => $validate_data['role'],
'password' => bcrypt($validate_data['password'])
]);
use this code
$user->name=$validate_data['name'];
$user->email=$validate_data['email'];
$user->status=$validate_data['status'];
$user->role_id=$validate_data['role'];
$user->password=bcrypt($validate_data['password']);
$user->save();
I am having trouble retrieving form values using the Illuminate\Http\Request class.
I have an endpoint that creates a product and another that updates it set up like this
Route::post('products', 'ProductController#store');
Route::put('products/{product}', 'ProductController#update');
The store and update methods in the ProductController are
public function store(Request $request)
{
// validate inputs
$validator = Validator::make($request->all(), [
'name' => 'required',
'category' => 'required',
'status' => 'required',
'price' => 'required',
'image' => 'required|image|mimes:jpeg',
'interest' => 'required'
]);
// return 401 response if validation fails
if ($validator->fails()) {
return response()->json([$validator->errors()], 401);
}
// create & store the product
if ($product = Product::create([
'name' => $request->name,
'category' => $request->category,
'status' => $request->status,
'price' => $request->price,
'interest' => $request->interest,
])) {
// store the product image
$file = $request->file('image');
$destinationPath = "public/images/products";
$filename = 'pramopro_' . $product->name . '_' . $product->id . '.' . $file->extension();
Storage::putFileAs($destinationPath, $file, $filename);
ProductImage::create([
'product_id' => $product->id,
'name' => $filename
]);
}
// return new product
return new ProductResource($product);
}
public function update(Request $request, Product $product)
{
// dd($request);
// validate inputs
$validator = Validator::make($request->all(), [
'name' => 'required',
'category' => 'required',
'status' => 'required',
'price' => 'required',
'image' => 'required|image|mimes:jpeg',
'interest' => 'required'
]);
// return 401 response if validation fails
if ($validator->fails()) {
return response()->json([$validator->errors()], 401);
}
// update this product
if ($product) {
$product->update($request->all());
return new ProductResource($product);
} else {
return response()->json(["error" => "Not found"], 404);
}
}
Now when I test the endpoints in postman, I can successfully create a new product record. But if I try to update a product, I get a 401 unauthorized error even though all the required fields are filled. dd($request)returns null but dd($product) returns the product as expected.
Maybe I have been looking at it so hard so I have missed something. What am I doing wrong?
This is the reasons I think why the $request return null
The store and update request is same name. Two input name or select name or textarea name can't be the same name in the same web page. If its same it will always get the first one that is the reason why it is returning null because the first one is empty.
The name you're calling is incorrect
Hope it helps!
I'm trying to store an image in my Laravel project, but I'm having an issue. The image is sucessfuly being added to the /public/images folder as its filename, but when the request hits the database, its added as /private/var/tmp/XXXXX. I've tried to set $request->file as the name, but it still posts as the var/temp.
Controller
public function store(Request $request)
{
$rules = [
// 'address' => 'required',
// 'city' => 'required',
// 'postcode' => 'required',
// 'restDesc' => 'required',
// 'telNumb' => 'required',
// 'resWebsite' => 'required',
// 'restDesc' => 'required',
// 'business_id' => 'unique:busprofiles,business_id',
];
$customMessages = ["Message"];
if ($request->hasFile('file')) {
$request->file->store('public/uploads');
$filename = $request->file->getClientOriginalName();
$filesize = $request->file->getClientSize();
$request->file = $request->file->storeAs('public/uploads', $filename);
}
$this->validate($request, $rules, $customMessages);
Busprofile::create($request->all());
return redirect()->route('business.dashboard')
->with('success', 'Profile created successfully');
}
If it helps: return $request->file returns the correct URL.
The problem is in Busprofile::create($request->all());. You do indeed get the original filename with $filename = $request->file->getClientOriginalName(); but your request stays the same.
Create the array for the database entries manually, according to your database needs.
$data = ['filename' => $request->file->getClientOriginalName(),
...,
];
and
Busprofile::create($data);