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
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 am pretty new to Laravel, and I am facing an issue.
I creating a website where users can upload products (modules) to the site and for their product they have to choose a category aswell as subcategory.
Now, I want to create a view.blade which automatically displays all the uploaded products with their corresponding subcategory. So on the roof page I want to display all the uploaded modules with subcategory roof.
However, the view page is loaded but no data is displayed...
I have created a ModulesController:
{ class ModulesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function create()
{
return view('modules/create');
}
public function store()
{
$data = request()->validate([
'title' => ['required', 'string', 'max:50'],
'description' => ['required', 'string', 'max:255'],
'price' => ['required', 'string'],
'category' => ['required', 'string'],
'subcategory' => ['required', 'string'],
'image' => ['required', 'image'],
]);
#dd($data);
$imagePath = request('image')->store('uploads', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1200, 1200);
$image->save();
auth()->user()->modules()->create([
'title' => $data['title'],
'description' => $data['description'],
'price' => $data['price'],
'category' => $data['category'],
'subcategory' => $data['subcategory'],
'image' => $imagePath,
]);
return redirect('/profile/' . auth()->user()->id);
}
public function show(\App\Models\Module $module)
{
return view('modules.show', compact('module'));
A corresponding model:
class Module extends Model
{
protected $fillable =[
'title',
'description',
'price',
'category',
'subcategory',
'image',
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
A Module migration database:
class CreateModulesTable extends Migration
{
public function up()
{
Schema::create('modules', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->text('description');
$table->string('price');
$table->string('category');
$table->string('subcategory');
$table->string('image');
$table->timestamps();
$table->index('user_id');
});
}
And I am trying to pass it to this view where I want to show all the images.
I have tried to use this loop but I can't make it work....
#section('content')
<div class="container">
<div class="flex justify-center pt-8 sm:justify-start
sm:pt-0">
<h1>All modules with corresponding subcategory</h1>
#if ( $module["subcategory"] == "dak" )
#foreach ($modules as $module)
<a href="/module/{{ $module->id }}">
<img src="/storage/{{$module->image}}"
class="w-100" alt=""/>
<a/>
#endforeach
#endif
</div>
</div>
#endsection
If anyone can help this would be much appreciated.
P.S. "dak" is a subcategory and means "roof".
There's a table in my SQL DB called "projects" and it has a column in it "categories" which is a varchar(255) representation of a php array "['category_1', 'category_2', 'category_3']" and what i'd like to do is put these categories into a separate table which would be made of a unique integer id in addition to the name of the category and then use a join table to connect it to "projects" in a many-to-many relationship.
So it would be a migration that would perform the following:
Create a join table called "categories_projects"
Create a table called "categories" that would be comprised of just a unique id and the title of the category
Insert into the categories a row for each so "category_1", "category_2", "category_3"
Look for any existing rows in the "projects" table and based on the varchar(255) field "category" mentioned above, create a row in the join table that would connect it to its respective category.
What I have so far:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('parent_id')->nullable();
$table->string('title');
$table->timestamps();
$table->softDeletes();
});
DB::table('categories')->insert(
[
'title' => 'category_1'
], [
'title' => 'category_2'
], [
'title' => 'category_3'
], [
'title' => 'category_4'
], [
'title' => 'category_5'
]
);
Schema::create('categories_projects', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('project_id');
$table->unsignedInteger('category_id');
$table->timestamps();
$table->softDeletes();
});
// This doesn't work but it's a representation of what I'm trying to do
// $categories = DB::rawQuery('select * from categories');
// foreach ($categories as $category) {
// $projects = DB::rawQuery('select * from projects where projects.category like %$category['title']');
// foreach($projects as $project) {
// DB::table(categories_projects)->insert(['project_id' => $project['id'], 'category_id' => $category['id']]);
// }
//
// }
}
Try this one:
If both sides of your categories name in your main table are surrounded by single quotes (such as 'category_1')
$categories = DB::rawQuery("select * from categories");
foreach ($categories as $category) {
$projects = DB::rawQuery("select * from projects where category like '%''" . $category["title"] . "''%' ");
foreach($projects as $project) {
DB::table('categories_projects')->insert(['project_id' => $project['id'], 'category_id' => $category['id']]);
}
}
This is what I ended up going with, it seems like I answered my own question in the process of asking it but anyways:
public function up()
{
Schema::dropIfExists('categories');
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->timestamps();
$table->softDeletes();
});
DB::table('categories')->insert([
['title' => 'Addition'],
['title' => 'Bathrooms'],
['title' => 'Commercial'],
['title' => 'Community'],
['title' => 'Dental'],
['title' => 'Design & Construction'],
['title' => 'Facade'],
['title' => 'Home Design'],
['title' => 'Medical'],
['title' => 'Multi-Family'],
['title' => 'Office'],
['title' => 'Renovation'],
['title' => 'Residential'],
['title' => 'Restaurant'],
['title' => 'Retail'],
['title' => 'Student Housing']
]);
Schema::create('categories_projects', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('project_id');
$table->unsignedInteger('category_id');
$table->timestamps();
$table->softDeletes();
});
$categories = DB::table("categories")->get();
foreach ($categories as $category) {
$category_id = $category->id;
$projects = DB::table('projects')->where('categories', 'like', '%'.$category->title.'%')->get();
$category_proj = [];
foreach ($projects as $project) {
$project_id = $project->id;
$category_proj[] = ['project_id' => $project_id, 'category_id' => $category_id];
}
DB::table('categories_projects')->insert($category_proj);
}
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('categories_projects');
Schema::dropIfExists('categories');
}
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');
}
}
I learn Laravel from udemy.com and I have a problem with migrate:refresh command. So, when I try use it I'll see information
Array to string conversion
I try solve my problem so propably I made new mistakes so it's my code:
Into UserTableSeeder
public function run()
{
App\User::create([
'name' => 'Kati',
'email' => 'hello#hello.pl',
'password' => bcrypt('password'),
'admin' => 1
]);
App\Profile::create([
'user_id' => $user->id,
'avatar' => 'link to avatar',
'about' => 'Interested description',
'youtube' => 'youtube.com',
'facebook' => 'facebook.com'
]);
}
Into migrations
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->text('about');
$table->string('youtube');
$table->string('facebook');
$table->timestamps();
});
}
And
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->boolean('admin')->default(0);
$table->rememberToken();
$table->timestamps();
});
}
I tryed clone my respository from github and refreshing but I had this some problem.
This should work:
public function run()
{
$user = App\User::create([
'name' => 'Kati',
'email' => 'hello#hello.pl',
'password' => bcrypt('password'),
'admin' => 1
]);
App\Profile::create([
'user_id' => $user->id,
'about' => 'Interested description',
'youtube' => 'youtube.com',
'facebook' => 'facebook.com'
]);
}
In your run statement your referencing in the App\Profile creation process the variable $user->id. However, it is not instantiated yet.
In addition, you are trying to add an avatar to your profile, therefore you should add this to the Profile-table or, like I did it, delete it from your seeder.
I solved it in my seeder:
'user_id' =>\App\User::pluck('id')->random();