Laravel Dropzone with product info - php

I'm looking for solution to use dropzoneJs in laravel 5.5 while writing my products.
What I want to do is: upload my images and fill my product info then save all together just like WordPress/Joomla etc.
What do I have so far:
Images Table
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('image');
$table->integer('product_id')->nullable()->unsigned();
$table->timestamps();
});
Schema::table('images', function($table) {
$table->foreign('product_id')->references('id')->on('products');
});
}
My form in Products create.blade.php
<div class="row">
<div class="col-md-12">
{!! Form::open([ 'route' => [ 'dropzone.store' ], 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone', 'id' => 'image-upload' ]) !!}
{{ csrf_field() }}
<div>
<h4 style="text-align: center;color:#428bca;">Drop images in this area <span class="glyphicon glyphicon-hand-down"></span></h4>
<!-- Input code below Not working yet -->
<input type="text" name="product_id" value="" hidden>
</div>
{!! Form::close() !!}
</div>
</div>
My JavaScript code:
<!-- drozone -->
<script type="text/javascript">
Dropzone.options.imageUpload = {
maxFilesize: 5, //MB
acceptedFiles: ".jpeg,.jpg,.png,.gif"
};
</script>
My ImageController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Image;
use App\Product;
class ImageController extends Controller
{
public function dropzone()
{
return view('dropzone-view');
}
public function dropzoneStore(Request $request)
{
$image = $request->file('file');
$imageName = time().$image->getClientOriginalName();
$image->move(public_path('images'),$imageName);
return response()->json(['success'=>$imageName]);
}
}
And my routes:
Route::get('dropzone', 'ImageController#dropzone');
Route::post('dropzone/store', ['as'=>'dropzone.store','uses'=>'ImageController#dropzoneStore']);
Any Idea On That?

Related

Attempt to read property "id" on null LARAVEL8

I'm new to laravel and I'm learning it from laracast.
Here is my problem, I'm creating a comment form and it's php code looks like this:
<section class="col-span-8 col-start-5 mt-10 space-y-6">
<!-- Post form -->
<form method="POST" action="/post/{{ $post->slug }}/comments" class="border border-gray-200 p-6 rounded-xl">
#csrf
<header class="flex items-center">
<img src="https://i.pravatar.cc/100?id={{ auth()->id() }}" alt="" width="40" height="40" class="rounded-full">
<h2 class="ml-3 ">Want to participate?</h2>
</header>
<div class="mt-6">
<textarea class="w-full text-sm focus:outline-none focus:ring"
name="body"
cols="30" rows="10"
placeholder="Quick,think of something to say!" ></textarea>
</div>
<div>
<button type="submit" class="bg-blue-500 text-white uppercase font-semi-bold text-xs py-2 px-10 rounded-2xl hover:bg-blue-600">Post</button>
</div>
this is the corresponding route:
Route::post('post/{post:slug}/comments',[PostCommentsController::class, 'store']);
Controller:, and I suspect there could be something wrong here 'user_id'=> request()->user()->id, and I tried numerous ways for this approach like auth()->id, Auth::user()->id
<?php
namespace App\Http\Controllers;
use App\Models\Post;
class PostCommentsController extends Controller
{
public function store(Post $post){
request()->validate([
'body'=>'required'
]);
$post->comments()->create([
'user_id'=> request()->user()->id,
'body' => request('body')
]);
return back();
}
}
and this the migration table for comment
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->text('body');
$table->timestamps();
migration table for post:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('category_id');
$table->string('slug')->unique();
$table->string('title');
$table->text('excerpt');
$table->text('body');
$table->timestamps();
$table->timestamp('published_at')->nullable();
});
If I click on post button I get the above error,tried my best to solve this problem but I couldn't. Can someone help me what's wrong with my code ?. My question may look naive as I'm new to stackoverflow community
use this code for controller
class PostCommentsController extends Controller
{
public function store(Post $post){
request()->validate([
'body'=>'required'
]);
$post->comments()->create([
'user_id'=> optional(auth()->user())->id,
'body' => request('body')
]);
return back();
}
}
user must logged in
first you must logged in
and in your route you must define your middleware if you are trying to get authenticated user's id like this
Route::post('post/{post:slug}/comments',[PostCommentsController::class, 'store'])->middleware('auth');
after that in your method/function inside controller use 'Request' class(not model class name) when you try to retrieve input from form
Laravel's 'Illuminate\Http\Request' class provides an object-oriented way to interact with the current HTTP request being handled by your application as well as retrieve the input, cookies, and files that were submitted with the request.
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request; //don't forget this
class PostCommentsController extends Controller
{
public function store(Request $request){
request()->validate([
'body'=>'required'
]);
$post->comments()->create([
'user_id'=> auth()->user()->id,
'body' => request('body')
]);
return back();
}
}

Multiple Image upload using Laravel 5.6

I'm using dynamic input generate function through that I try to upload multiple images upload I got code from the internet and I modified according to my requirement images uploading is working when I the name into the table that time only I'm getting issues.
I can't understand how to do that. Please help how to do that.
I attached my codes, UI, table screenshot.
Inserting Code
$Colorimages=array();
if($files=$request->file('Colorimages'))
{
foreach($files as $file)
{
$extension = $file->getClientOriginalExtension();
$filename = date('YmdHis').rand(1,9999).'.'.$extension;
$file->move(public_path("product_images/sub_images"), $filename);
$Colorimages[]=$filename;
}
}
if(count($request->prol_product_line_code)>0)
{
foreach ($request->prol_product_line_code as $prol=>$v)
{
$data2=array
(
'prol_product_code' => $request->prod_product_code,
'prol_product_line_code' => $request->prol_product_line_code[$prol],
'prol_printed' => $request->prod_printed,
'prol_color' => $request->prol_color[$prol],
'prol_image1' => $Colorimages[$prol],
'prol_image2' => $Colorimages[$prol],
'prol_image3' => $Colorimages[$prol],
);
product_line::insert($data2);
}
}
This is the way to upload multiple images in laravel.
Step 1: Create Routes(routes/web.php)
Route::get('image-view','ImageController#index');
Route::post('image-view','ImageController#store');
Step 2: Create ImageController File(app/Http/Controllers/appController.php)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ImageController extends Controller
{
public function index()
{
return view('image-view');
}
public function store(Request $request)
{
$imageName = request()->file->getClientOriginalName();
request()->file->move(public_path('upload'), $imageName);
return response()->json(['uploaded' => '/upload/'.$imageName]);
}
}
Step 3: Create Blade File(resources/views/index.blade.php)
<div class="container">
<div class="row">
<div class="col-lg-8 col-sm-12 col-11 main-section">
<h1 class="text-center text-danger">File Input Example</h1><br>
{!! csrf_field() !!}
<div class="form-group">
<div class="file-loading">
<input id="file-1" type="file" name="file" multiple class="file" data-overwrite-initial="false" data-min-file-count="2">
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$("#file-1").fileinput({
theme: 'fa',
uploadUrl: "/image-view",
uploadExtraData: function() {
return {
_token: $("input[name='_token']").val(),
};
},
allowedFileExtensions: ['jpg', 'png', 'gif'],
overwriteInitial: false,
maxFileSize:2000,
maxFilesNum: 10,
slugCallback: function (filename) {
return filename.replace('(', '_').replace(']', '_');
}
});
</script>

Laravel: migration default() field does not work

i having troubles with my migration field default('No description'), i need to save a default value for my null fields on my form, but when i save, my form data stores empty fields.. why? i'm working with Laravel 5.2 and it is my code:
public function up()
{
Schema::create('combos', function (Blueprint $table) {
$table->increments('id');
$table->string('item_name');
$table->string('description')->nullable()->default('No description');
$table->decimal('price', 5, 2);
$table->decimal('buy_price', 5, 2);
$table->timestamps();
});
}
My view:
<div class="form-group">
{!! Form::label('item_name','Item: ',['class'=>'control-label col-md-2']) !!}
<div class="col-md-7" >
{!! Form::text('item_name',null,['class'=>'form-control','placeholder'=>'Enter a item name','required','min'=>5]) !!}<br/>
</div>
</div>
<div class="form-group">
{!! Form::label('price','Price: ',['class'=>'control-label col-md-2']) !!}
<div class="col-md-7" >
{!! Form::text('buy_price',null,['class'=>'form-control','placeholder'=>'Enter a price','required']) !!}<br/>
</div>
</div>
in your store function do this
$input = $request->all();
$input['description'] = $request->description;
Combos::create($input);

How to Set Url for Update Data in Laravel 5.2

My Friend
my problem with URL $category in Laravel update post
my view update post:
{{--insert category--}}
<div class="col-sm-6">
{{Form::model($category,['method'=>'patch','url'=>['category/update',$category->id]])}}
<div class="form-group">
<div class="form-group">
{{form::text('category','',['class'=>'form-control text-right','placeholder'=>'submit'])}}
</div>
{{form::submit('submit',['class'=>'btn btn-primary'])}}
</div>
{{Form::close()}}
</div>
my route :
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('update/{id}', 'categoryController#update');
});
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::post('update/{id}', 'categoryController#patchUpdate');
});
my controller:
public function update($id){
Category::find($id);
return view('admin.updateCategory',compact('id'));
}
public function patchUpdate($id,request $request){
$category = Category::find($id);
return redirect('category');
}
my error is:
Undefined variable: category (View: C:\wamp\www\pc\resources\views\admin\updateCategory.blade.php)
You're passing the $id to the view instead of the category
public function update($id){
$category = Category::find($id);
return view('admin.updateCategory',compact('category'));
}
this error fixed by change form::open :
{{Form::open()}}
<div class="form-group">
<div class="form-group">
{{form::text('category','',['class'=>'form-control text-right','placeholder'=>'submit'])}}
</div>
{{form::submit('submit',['class'=>'btn btn-primary'])}}
</div>
{{Form::close()}}

Edit a form with Laravel Framework

I'm new to laravel and trying to learn using it. I created a little project for threads. Nothing special. The thing is, the function to edit something doesn't work and I cant see why. Maybe someone of you see the mistake?
thats my Routes:
Route::get('/index', 'Test\\TestController#index');
Route::get('/add', 'Test\\TestController#add');
Route::post('/test', 'Test\\TestController#store');
Route::get('/show/{id}', 'Test\\TestController#show');
Route::get('/show/{id}/edit', ['as' => 'edit', 'uses' => 'Test\\TestController#edit']);
Route::put('/show/{id}/edit', ['as' => 'editing', 'uses' => 'Test\\TestController#update']);
thats the important parts of the edit method:
public function edit($id) {
$thread = Thread::query()->findOrFail($id);
return view('test.edit', [
'thread' => $thread
]);
}
public function update($id, StoreRequest $request) {
$thread = Thread::query()->findOrFail($id);
$thread->fill($request->all());
$thread->save();
return redirect(action('Test\\TestController#show', [$thread->id]));
}
}
show.blade
#extends('master')
#section('content')
<div class="panel panel-primary">
<div class="panel-heading">
<div class="panel-title">
{{ $thread->thread }}
</div>
</div>
<div class="form-body">
<div class="form-group"><br>
<ul>
{{$thread->content }}<br><br>
{{$thread->created_at->format('d.m.Y H:i:s')}}
</ul>
</div>
</div>
<div class="panel-footer">
<div class="btn btn-primary">Thread bearbeiten</div>
</div>
</div>
#stop
edit blade ( formular where the text I want to add is in the textbox and the save button )
#extends('master')
#section('content')
{!! Former::horizontal_open()->method('PUT')->action(action("Test\\TestController#update", [$thread->id])) !!}
{!! Former::populate($thread) !!}
{!! Former::text('thread')->label('Thread') !!}
{!! Former::text("content")->label("Content") !!}
{!! Former::large_primary_submit('Save!') !!}
{!! Former::close() !!}
#stop
model:
<?php
namespace App\Models\Thread;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model {
public $table = 'thread';
public $fillable = [
'thread',
'content',
];
}
ERROR MESSAGE :
No query results for model [App\Models\Thread\Thread].

Categories