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".
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]);
}
This is a continuation of my last question.
I like to create a relationship between a user (with an account type that’s equal to a “profile”) and my job posts. What I did was create a relationship like this in my models (not sure if correct tho)
User.php
public function jobposts()
{
$this->hasMany(JobPost::class)->where('account_type', 'profile');
}
JobPost.php
public function userprofile()
{
$this->belongsTo(User::class)->where('account_type', 'profile');
}
JobPostController.php
public function store(Request $request)
{
$this->validate($request, [
'job_name' => 'required|max:100',
'describe_work' => 'required|max:800',
'job_category' => 'required|not_in:0',
'city' => 'required|not_in:0',
'state' => 'required|not_in:0',
'zip' => 'required|regex:/\b\d{5}\b/',
]);
dd(auth()->user()->jobpost()->job_name);
}
2021_11_20_211922_create_job_posts_table.php
Schema::create('job_posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->contrained()->onDelete('cascade');
$table->string('job_name');
$table->text('describe_work');
$table->string('job_category');
$table->timestamps();
});
Got 2 questions about what I can do in the JobPostController.php.
How do I dd() to test the output?
This seems wrong
dd(auth()->user()->jobpost()->job_name);
How do I add it correctly into the DB like this?
public function store(Request $request)
{
$request->user()
->jobpost()
->create([
'job_name' => $request->job_name
]);
}
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
when I send data from form to database
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'fypp.joblisting' doesn't exist (SQL: select count(*) as aggregate from `joblisting` where `email` = )
this error occurs. In my database joblistings table exists but laravel looking for the singular name instead of the plural table name. Even I have created new model with new migration and everything but still facing this issue.
model code
class Joblisting extends Model
{
use HasFactory;
protected $fillable = [
'title',
'category',
'company',
'email',
'level',
'number',
'description',
];
}
controller code
class JoblistingController extends Controller
{
public function showForm()
{
return view('frontend.pages.addjob');
}
public function createjob(Request $request)
{
$this->validate($request,[
'title'=> 'required|string',
'category'=> 'required',
'company' =>'required',
'email' => 'required|unique:joblisting',
'level' => 'required',
'number' => 'required',
'description' => 'required',
]);
Joblisting::create([
'title' => $request->title,
'category' => $request->category,
'company'=> $request->company,
'email'=> $request->email,
'level'=> $request->level,
'number'=> $request->number,
'description'=> $request->description,
]);
return redirect('viewlist')->with('success', 'job posted successfully');
}
}
migration code
class CreateJoblistingsTable extends Migration
{
public function up()
{
Schema::create('joblistings', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('category');
$table->string('company');
$table->string('email');
$table->string('level');
$table->string('number');
$table->string('description');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('joblistings');
}
}
You have to use like this
'email' => 'required|unique:joblistings',
Laravel uses snake case, hence:
Fix 1:
use controller name as JobListingController
Fix 2:
in your model, add tthe following line:
protected $table = 'joblistings';
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');
}
}