I want to keep track of users download on my web application so I decide to create a tables called downloads. I already assign the relation in my model.
Download.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Download extends Eloquent {
protected $table = 'downloads';
// Relations
public function user(){return $this->belongsTo('User','user_id');}
public function catalog_downloads(){return $this->hasMany('CatalogDownload'); }
public function marketing_materials(){return $this->hasMany('Download'); }
}
Here is my download function in one of my controller
public function file_download($id)
{
$catalog_download = CatalogDownload::findOrFail($id);
$distributor = Auth::user()->distributor()->first();
$export_type = $distributor->export_type()->first();
$product_export = $catalog_download->product_exports()->first();
$destinationPath = base_path().'/app/files/product_export/'. $catalog_download->id.'/'. $export_type->id.'/';
$file_name = $product_export->file_path;
$pathToFile = $destinationPath .$file_name;
if(Response::download()){
$download = new Download;
$download->title = $catalog_download->title;
$download->count = $download->count + 1;
$download->user_id = Auth::user()->id ;
$download->save();
}
return Response::download($pathToFile);
}
I have downloads table already.
For some reasons, no data has been save to the database. :(
Can someone help me take a look into this ?
I just added this block of code.
if(Response::download()){
$download = new Download;
$download->title = $catalog_download->title;
$download->count = $download->count + 1;
$download->user_id = Auth::user()->id ;
$download->save();
}
The rest is all correct.
you have a return statement before your code, it is unreachable, you cannot do anything after a return...
Related
I am trying to make my code more readable and reusable along my app.
I created for this purpose a Trait but I couldn't use it (probably I didn't understand the right way to import it).
My code is as follows:
Trait
namespace App\Http\Traits;
use App\Models\FlightManagement\Aircraft;
use App\Models\FlightManagement\FunctionType;
use App\Models\FlightManagement\LogEntry;
use Illuminate\Support\Facades\Request;
trait FlightTrait
{
public function store_new_flight(Request $request, $log_entry)
{
$log_entry->aircraft_id = $request->aircraft_id;
$log_entry->adep_id = $request->adep;
$log_entry->ades_id = $request->ades;
$log_entry->date = date('Y-m-d', strtotime($request->date));
$log_entry->atd = $request->atd;
$log_entry->ata = $request->ata;
$log_entry->operational_condition_id = $request->operational_condition_id;
$log_entry->function_type_id = $request->function_type_id;
$log_entry->instructor_id = $request->instructor_id;
$log_entry->student_id = $request->student_id;
$eet = date('H:i', (strtotime($request->ata)) - (strtotime($request->atd)));
if ($request->ata <= $request->atd) {
return redirect()->back()->with('error', 'ATA can not be greater or equal to ATD');
}
$function_type_obj = FunctionType::find($request->function_type_id)->name;
if ($function_type_obj == 'Dual Command' and $request->instructor_id == '') {
return redirect()->back()->with('error', 'Instructor Must be on Board!!!');
}
if ($function_type_obj == 'Single Pilot') {
$log_entry->solo_flight = 1;
}
$aircraft_obj = $request->aircraft_id;
$aircraft_type_obj = Aircraft::find($aircraft_obj)->aircraft_type->name;
if ($aircraft_type_obj == 'MEP') {
$log_entry->mep_flight = 1;
}
if ($aircraft_type_obj == 'SIM') {
$log_entry->sim_flight = 1;
}
$log_entry->eet = $eet;
$log_entry->save();
return $log_entry;
}
}
Basically my final goal is to use it inside a controller function as follows:
Controller
use App\Http\Traits\FlightTrait;
class LogEntryController extends Controller
{
use FlightTrait;
public function store_new_flight(Request $request)
{
$log_entry = new LogEntry();
$log_entry->$this->store_new_flight($request, $log_entry);
return redirect()->route('flight.list')->with('success', 'Flight Added Successfully');
}
}
I know that the problem is likely to be in the way I call the trait function, but I googled around and I couldn't find anything.
The error is giving me is:
Error
Object of class App\Http\Controllers\FlightManagement\LogEntryController could not be converted to string
I basically have this:
foreach ($request->input('images', []) as $imagesData) {
$images = new ScenesImages($imagesData);
$images->product()->associate($product);
$images->save();
}
This saves correctly in my foreign key the name of the image/s but how do I safe the image path dynamicly here.
If I dd($product);
I get this:
> #attributes: array:2 [▼
> "name" => "test"
> "product_id" => 7 ]
but no img(path)
Javascript which creates that html in a loop:
for(var i = 1; i<slider.value; i++) {
$('#sliderAppendSz').append(
'<div class=\"form-group\">'
+'<div class=\"fileinput fileinput-new\" data-provides=\"fileinput\">'
+'<div class=\"input-group\">'
+'<input name=\"images['+i+'][name]\" type=\"text\">'
+'<span class=\"input-group-btn\">'
+'<span class=\"btn btn-primary btn-file\">'
+'<input name=\"images['+i+'][scenes_images]\" type=\"file\" multiple class=\"ImageInput\" accept=\"file_extension/*\">'
+'</span>'
+'</span>'
+'</div>'
+'</div>');
}
And my ScenesImages Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ScenesImages extends Model
{
protected $table = 'scenes_images';
protected $fillable = ['product_id', 'name', 'scenes_images'];
public function product()
{
return $this->belongsTo('App\Product', 'product_id');
}
}
And here my Product Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public static $projects = 'C:\\xampp\\htdocs\\MyProject\\Web';
protected $table = 'products';
protected $fillable = [
'scenes_images'
];
public static $rules = [
'scenes_images' => 'max:500',
];
public function scenesImages()
{
return $this->hasMany('App\ScenesImages');
}
}
Edit:
OK I think I got it I had to add this as since I only got input before I just added a foreach with a file, my question now is if it is somehow possible to sum the two foreach loops into one like $requesting->file and input.
foreach ($request->file('images', []) as $imagesData) {
$images = new ScenesImages($imagesData);
$images->product()->associate($product);
$images->save();
}
Could be better if you show us more information about the model ScenesImages, otherwise maybe you can have something like this.
foreach ($request->input('images', []) as $imagesData) {
$images = new ScenesImages($imagesData);
$images->product()->associate($product);
$images->path = $your_path
$images->save();
}
Of course you will need the variable $your_path with the path where is saved the images or if it's an url from Amazon S3, but as I said we need maybe more information about your Models structure.
Don't forget upload the image, save it to the server
foreach ($request->input('images', []) as $imagesData)
{
$images = new ScenesImages($imagesData);
$images->product()->associate($product);
$destinationPath = 'uploads'; // upload path
$extension = $imagesData->getClientOriginalExtension(); // getting image extension
$fileName = $imagesData->getClientOriginalName()'.'.$extension; // renameing image
$imagesData->move($destinationPath, $fileName); // uploading file to given path
$images->path = $destinationPath.'/'.$fileName;
$images->save();
}
Couple of issues I'm having with your code:
I'm a bit confused on what $request->file('images') returns. If it's an array of the UploadedFile object then I'm pretty sure you're doing it wrong. You're not even uploading the images to your server, once uploaded that's the file path you want to use when saving your ScenesImages model.
Your code here:
$images = new ScenesImages($imagesData);
is newing up a ScenesImages object and passing it a variable which would need to satisfy the model's required attributes to be created properly, its attributes being: name, scenes_images according to your question code. If you don't it's not going to work properly. You should be passing it an associative array with the keys matching the attributes the model has.
You should usually make your tables plural: scene_images and then your model singular: SceneImage
Consider doing your code like this:
$product = Product::first(); // assume you've defined this already
$uploadedImages = $request->file('images'); // get the images
$destinationPath = storage_path . '/uploads'; // somewhere to put your images
foreach ($uploadedImages as $uploadedImage) {
// upload the image first!
if ($uploadedImage->isValid()) {
$extension = $uploadedImage->getClientOriginalExtension(); // file extension
$uploadedImageName = uniqid(). '.' .$extension; // unique file name with extension
$uploadedImage->move($destinationPath, $uploadedImageName); // move file to our uploads path
// create ScenesImages record in DB
$image = ScenesImages::create([
'name' => $uploadedImageName, // assuming this is your file path?
'scenes_images' => '' // assign something here, not sure what it's supposed to be?
]);
// associate product
$image->product()->associate($product);
} else {
// handle error here
}
}
I am working on a laravel-4 application. Currently It is coming together nicely and I've been getting my head around defining the relationships between the various table s of the database. However I've run into a problem that I'm having trouble solving.
In my db there is a resources table and tags table. There is a many to many relationship between them so I've also got a resource_tags table which has both tables id as the foreign keys.
Now, when I am creating a resource based on data provided by the user via a form I create the resource, check the type and decide on an action. Then I retrieve the tags of the resource and loop through them and create an entry into the Tags table.
My issue is placing information into the resource_tags table. Is there a method that can enable me to do this with relative ease?
This is my controller that is handling the form submission:
class SharedResourcesController extends BaseController {
//Add a shared Resource to the DB
//To do: Error checking and validation.
public function handleResource(){
//Create Object
$resource = new SharedResource;
$resource->title = Input::get('title'); //Title of resource
$resource->user_id = Input::get('user_id'); //User who uploads
$resource->book_id = Input::get('book_id'); //Book it is associated with
$resource->type_id = Input::get('type_id'); //Type of resource
//STORE LINKS
//if type is link... 1
if($resource->type_id == "1"){
$resource->web_link = Input::get('link');
}
//if type is video...2
if($resource->type_id == "2"){
$resource->vid_link = Input::get('link');
}
//UPLOADING
//If type is doc...3
if($resource->type_id == "3"){
if(Input::hasFile('file')){
$destinationPath = '';
$filename = '';
$file = Input::file('file');
$basename = Str::random(12);
$extension = $file->getClientOriginalExtension();
$destinationPath = public_path().'/file/';
$filename = Str::slug($basename, '_').".".$extension;//Create the filename
$file->move($destinationPath, $filename);
$resource->doc_link = $filename;
}
}
//if type is img...4
if($resource->type_id == "4"){
if(Input::hasFile('file')){
$destinationPath = '';
$filename = '';
$file = Input::file('file');
$basename = Str::random(12);
$extension = $file->getClientOriginalExtension();
$destinationPath = public_path().'/img/uploads/';
$filename = Str::slug($basename, '_').".".$extension;//Create the filename
$file->move($destinationPath, $filename);
$resource->img_link = $filename;
}
}
//TAGS
//Get the tags
$tags = Array();
$tags = explode(',', Input::get('tags'));
foreach($tags as $tag){
//Create a new Tag in DB - TO DO: Only Unique TAGS
$newTag = new Tag;
$newTag->name = $tag;
$newTag->save();
//Enter to resource tags
}
//Entry to resouce_tags
//Save Object
$resource->save();
return Redirect::action('User_BaseController#getSharedResources')->with('success', 'Resouce Created!');
//Any errors return to Form...
}
}
MODELS
class SharedResource extends Eloquent{
//set up many to many
public function tags(){
return $this->belongsToMany('Tag');
}
and
class Tag extends Eloquent{
//set up many to many
public function sharedResources(){
return $this->belongsToMany('SharedResource');
}
I know that there is lots missing in terms of validation and error handling, but I'm just trying to get the flow working and I can modify it at a later date. I'd appreciate any help.
All you have to do is build or grab the Resource and build or grab the Tags then call saveMany on the resource's tags relationship and pass an array of tag items into it, like this (pseudo-codey example):
$resource = Resource::create(['name' => 'Resource 1']);
$tag = [];
for ($i = 5; $i > 0; $i--) {
$tag = Tag::create(['name' => 'Tag '.$i]);
array_push($tags, $tag);
}
$resource->tags()->saveMany($tags);
The $tags have to be an array of Tag objects, and the saveMany called on the relationship will take care of the pivot table insertions for you. You should end up with a Resource 1 resource in the resources table, five Tags in the tag table, and 5 records in the resource_tag table with the relationships saved.
Can you add the code for both of your models as well? Do you have the relationship defined in them?
For example:
class Resource extends Eloquent {
public function tags()
{
return $this->belongsToMany('tag');
}
}
and
class Tag extends Eloquent {
public function resources()
{
return $this->belongsToMany('resource');
}
}
I have 2 tables: listings and listings_specifications
Listings table
id
type
status
location
specifications_id
Listings_specifications table
id
listing_id
swimming_pool
water_well
I need to select the specifications (checkboxes) on the same form with which I add a listing. I have created all the forms, views, models, controllers but I think I got some logic wrong.
Listing.php model
protected $table = 'listings';
public function contact()
{
return $this->BelongsTo('contacts');
}
public function specifications()
{
return $this->BelongsTo('listings_specifications');
}
Specification.php model
protected $table = 'listings_specifications';
public function listings()
{
return $this->BelongsTo('listings');
}
ListingsController.php (where the data gets saved in the database)
$listing = new Listing;
$contact = new Contact;
$listing->status = Input::get('status');
$listing->listingfor = Input::get('listingfor');
$listing->propertystatus = Input::get('propertystatus');
$listing->propertytype = Input::get('propertytype');
$listing->userid = Auth::user()->id;
$listing->location = Input::get('location');
$listing->contact_id = $contact_id;
$listing->save();
$specifications = Specification::find($id);
if( $listings->save() ) {
$specifications = new Specification;
$specifications->listing_id = $id;
$specifications->swimming_pool = Input::get('swimming_pool');
$specifications->water_front = Input::get('water_front');
$specifications->save();
}
I'm getting this error: Undefined variable: id
Where did I go wrong?
Thank you
It looks like you have some logic errors.
First of all, you are never setting $id anywhere, but that's okay because you really don't need it.
Remove the $specifications = Specification::find($id); line because that's not doing anything.
Then change your last section to something like this...
if( $listings->save() ) {
$specifications = new Specification;
$specifications->swimming_pool = Input::get('swimming_pool');
$specifications->water_front = Input::get('water_front');
$listing->specifications()->save($specifications);
}
$listing->specifications()->save($specifications); will automatically save the new specification with the correct listing_id for you.
Modify your Listing model's specifications relationship to...
public function specifications()
{
return $this->hasMany('Specification');
}
I'm assuming here one listing can have many specifications. If not, you can easily just change that to a hasOne.
You use $id in the line $specifications = Specification::find($id); but you don't define it before.
I'm trying to maintain a skinny controller, but I'm still getting used to what can go in my controller, since before I used to pile just about everything inside of it. In this example I'm inserting validated data into a database, which I assumed is correct. What I'm confused about is that I want to take one of the field inputs, manipulate its text formatting and then save it to another field in my database. What I have written works, but I don't know if its good to have this code in my controller, if not where should it go?
Controller
public function store()
{
$validation = new Services\Validators\Deal;
if($validation->passes())
{
$deals = Deals::create(Input::all());
// start code in question
$image = Input::get('company');
$image = strtolower($image);
$image = str_replace(" ", "-", $image);
$image .= ".png";
$deals->image = $image;
$deals->save();
// end code in question
return Redirect::to('deals/create')
->with('message', 'Deal Created');
}
return Redirect::back()
->withInput()
->withErrors($validation->errors);
}
To recap, I'm not sure if the code in question belongs in my controller, and if it doesn't, where would it be better placed? Thanks for any insights.
Any business logic should be placed in models, or repositories and your controller should look just like
<?php
class DealsController extends controller {
public function __construct(Deals $deals) //// <---- Dependency Injection
{
$this->deals = $deals;
}
public function store()
{
try
{
$this->deals->insertRow(Input::all());
}
catch (\Exceptions\ValidationException $e)
{
return Redirect::back()
->withInput()
->withErrors($this->deals->errors);
}
return Redirect::to('deals/create')
->with('message', 'Deal Created');
}
}
And in your Deals class, you do whatever you need to do with your data
class Deals extends Eloquent {
public function insertRow($input)
{
$validation = new Services\Validators\Deal;
if($validation->passes())
{
$deals = Deals::create($input);
// start code in question
$image = $input['company'];
$image = strtolower($image);
$image = str_replace(" ", "-", $image);
$image .= ".png";
$deals->image = $image;
$deals->save();
// end code in question
}
$this->errors = $validation->errors;
throw new \Exceptions\ValidationException("Error inserting Deals", $validation->errors);
}
}
This is untested and a not-really-refactored code, but I hope you can see a point in it.
You could actually remove all the code in question and use Laravel Mutator instead.
Basically, setup a function in your Deals class which will automatically process the text formatting whenever data is about to be set/save via the Model Eloquent ::create, or update.
Something like
public function setImageAttribute($value)
{
$image = strtolower($value);
$image = str_replace(" ", "-", $image);
$image .= ".png";
$this->attributes['image'] = $image;
}
Refer to http://laravel.com/docs/eloquent#accessors-and-mutators