Slim: Multiple GET names for 1 url - php

I am trying to add a video section in my website using twig, slim, and eloquent. Now here is what I have for my route for my 'watch' pages
<?php
$app->get('/watch/:series/:episode', function($series, $episode) use($app){
$video = $app->video->where('series', $series)->where('episode', $episode)->first();
$app->render('videos/watch.php', [
'video' => $video
]);
})->name('videos.watch');
now what I want to do is also have it to where when if they do not specifiy an episode number (i.e. type in 'watch/seriesName/') it defaults to the lowest episode number. My database structure is 'id', 'title', 'series', 'episode' (all that really matter to this issue).
In the midst of asking this question I actually figured it out. I will answer my own question so that others who may have the same problem may know what I did.
Here is my video class just in case anyone is interested in how to utilize my video class (not sure if it was the best way of going about handling videos but it works)
<?php
namespace BiosystemStudios\Video;
use Illuminate\Database\Eloquent\Model as Eloquent;
use JBBCode\Parser;
use JBBCode\DefaultCodeDefinitionSet;
class Video extends Eloquent
{
protected $table = 'content_video';
protected $fillable = [
'title',
'series',
'episode',
'location',
'description',
'category',
'is_youtube',
'youtube_link',
'views'
];
public function getTitle()
{
return $this->title;
}
public function getDescription()
{
$parser = new Parser();
$parser->addCodeDefinitionSet(new DefaultCodeDefinitionSet());
$text = $this->description;
$parser->parse($text);
return $parser->getAsHtml();
}
public function getLocation()
{
return $this->location;
}

Rename the first get request to "videos.watch.episode" then create this get request:
$app->get('/watch/:series/', function($series) use($app){
$video = $app->video->where('series', $series)->first();
$app->render('videos/watch.php', [
'video' => $video
]);
})->name('videos.watch');

Related

Category isn't getting related video blogs?

I am trying to get category related video blogs by below code but i get nothing in var_dump? I want to get category related videos:
$category = VideoBlogCategoryModel::findFirst(1); // This returns category successfully and there are many video blogs having this category linked
var_dump($category->getVideoBlogs());exit;
VideoBlogModel.php
public function initialize(){
// Run base initialize code
parent::initialize();
// Configure Relation with VideoBlogCategoryModel
$this->belongsTo('category_id', VideoBlogCategoryModel::class, 'id', array(
'alias' => 'videoCategory',
'foreignKey' => true
));
}
public function getVideoCategory(){
return $this->videoCategory;
}
public function setVideoCategory($videoCategory){
$this->videoCategory = $videoCategory;
}
VideoBlogCategoryModel.php
public function initialize(){
// Run base initialize code
parent::initialize();
// Configure relation with VideoBlogModel
$this->hasMany('id', VideoBlogModel::class, 'category_id', array(
'alias' => 'videoBlogs',
'foreignKey' => true,
'cxAction' => static::ACTION_CASCADE_DELETE
));
}
public function getVideoBlogs(){
return $this->videoBlogs;
}
public function setVideoBlogs($videoBlogs){
$this->videoBlogs = $videoBlogs;
}
Let me know if anything else is required, I will share it.
In VideoBlogCategoryModel.php change
public function getVideoBlogs() {
return $this->videoBlogs;
}
to
public function getVideoBlogs() {
return $this->getRelated('videoBlogs');
}
Then try accessing it like:
$category = VideoBlogCategoryModel::findFirst(1);
$videos = $category->getVideoBlogs();
foreach( $videos as $video ) {
// access data here
var_dump($video->anyProperty()); // e.g $video->getId()
}
can you try it
$category = VideoBlogCategoryModel::findFirst(1);
$videos = $category->getVideoBlogs();
var_dump($videos->count());
var_dump($videos->toArray());
exit;
I think use var_dump for a Phalcon Collection Object is not a good idea, you can convert it to Array and Var_dump
Hope it can help you
Or try:
$categories = VideoBlogCategoryModel::findById($id);

zendframework routing based on the GET parameter

i have a page in my website (zendframework 1) that parses the GET parameter and query its data from the database to show it to the user.
-> my current url : https://example.com/index.php/product/info?id=123
i want my url to be more human readable
-> https://example.com/index.php/product/iphone-7s-white
so basicaly i want to parse the GET parameter in the url and query the name of the product from the database in order to make it appear as the page name in the url.
i came across some solutions, one of them is achieved by looping through the database (in bootstrap.php) and adding a route for each product, but this seems like a mess, (products can reach 200k or maybe more than that).
is there a better solution for my problem ? thanks in advance
So basically, ZF1 provides a default route that leads to the controller/action of the names from the url.
You can add custom routes from the application/Bootstrap.php file by adding a function there:
/**
* This method loads URL routes defined in /application/configs/routes.ini
* #return Zend_Router
*/
protected function _initRouter() {
$this->bootstrap('frontController');
$front = $this->getResource('frontController');
$router = $front->getRouter();
$router->addRoute(
'user',
new Zend_Controller_Router_Route('product/:slug', array(
'controller' => 'product',
'action' => 'details',
), array(
'slug' => '[A-Za-z0-9-]+',
))
);
return $router;
}
And here you go!
As described by Chris, you need to change your controller code to handle the request. Another solution would be to use an extra action.
final class ProductController
{
public function infoAction()
{
$product = $table->find($this->_param('id'));
$this->view->product = $product;
}
public function detailsAction()
{
$product = $table->fetch(['slug' => $this->_param('slug')]);
$this->view->product = $product;
$this->render('info');
}
}
Now, assuming you do a lot of processing in infoAction, you could go with a forward:
final class ProductController
{
public function infoAction()
{
$product = $table->find($this->_param('id'));
$this->view->product = $product;
}
public function detailsAction()
{
$product = $table->fetch(['slug' => $this->_param('slug')]);
$this->forward('info', 'product', [
'id' => $product->id,
]);
}
}
It is less efficient (2 requests instead of one), but allows you to reuse your code.

localization Faker\Factory does not work in laravel

I have a Post Model with these fields :
post_id
post_title
post_content
post_content_full
author
Now I want to use laravel sedders and model factories to create fake fa_IR localized data and insert to posts table.
For that I wrote this in database/factories/ModelFactory.php:
$factory->define(App\Post::class, function (Faker\Generator $faker) {
return [
'post_title' => $faker->sentence,
'post_content' => $faker->paragraph,
'post_content_full' => $faker->paragraph(3),
'author' => $faker->name
];
});
Then I created a PostsTableSeeder class like this :
use Illuminate\Database\Seeder;
class PostsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run ()
{
factory(App\Post::class, 5)->create();
}
}
And in AppServiceProvider.php added below codes to register function :
$this->app->singleton(FakerGenerator::class, function () {
return FakerFactory::create('fa_IR');
});
But After running the seed , laravel uses default locale (en_US) and ignores fa_IR.
I do not know what else to do.
Update:
Even I changed in DEFAULT_LOCALE const vendor/fzaninotto/faker/src/Faker/Factory.php to fa_IR Nothing changed.
Not all faker methods are supported in every language, from what a quick lookup of the documentation says, the Company and Address provider are supported in the fa_IR localization
Try this way
$factory->define(App\Post::class, function () {
$faker = Faker\Factory::create('fa_IR');
return [
'post_title' => $faker->sentence,
'post_content' => $faker->paragraph,
'post_content_full' => $faker->paragraph(3),
'author' => $faker->name
];
});
You need to change the faker locale in your app config file.
First run this
php artisan make:factory PostFactory
Do like this
$faker = \Faker\Factory::create();
Then use like this
$sub_g->name = $faker->name();
$sub_g->country = $faker->country();
$sub_g->state = $faker->state;
Thank me later.

How to use model attribute value in behavior config Yii

I want create ImageBehavior for uploading and saving images. My behavior have two fields: imagePath and imageField. In my model i'm wrote:
public function behaviors(){
return array(
'imageBehavior' => array(
'class' => 'ImageBehavior',
'imagePath' => 'images/avatar-pics/'.$this->user->username,
'imageField' => 'avatar',
),
);
}
but this doesn't worked - i receive path -
images/avatar-pics//image.png
What a solution? Create in behavior field imageFolder and add to config 'imageFolder' => 'user->username'? Thanks.
As a suggestion:
Change the way you use your behavior and add some codes to your models. Take a look at the following example:
For example, your behavior:
class ImageBehavior extends CBehavior {
public $imagePath;
public $imageField;
public function getImagePath() {
return $this->imagePath;
}
}
Your model:
class TestModel extends CFormModel {
private $imagePath = '/home/x/y';
public function setImagePath($imagePath) {
$this->imagePath = $imagePath;
$this->attachBehaviors(array(
array(
'class' => 'ImageBehavior',
'imagePath' => $this->imagePath
)
));
}
public function init() {
$this->setImagePath($this->imagePath);
parent::init();
}
}
Now, take a look at tests and results:
$model=new TestModel();
CVarDumper::dump($model->getImagePath()); //output: /home/x/y
$model->setImagePath('/home/x/path2');
CVarDumper::dump($model->getImagePath()); //output: /home/x/path2
$model->setImagePath('/home/x/path3');
CVarDumper::dump($model->getImagePath()); //output: /home/x/path3
By this way, if you do not set any imagePath it uses model's default value. In front, each time you change the imagePath your path will change in your behavior.
Note: This is just a suggestion. By this, you can customize your setImagePath method to get the value from everywhere you want(another model, session and so on...).
Sorry for answering own question, but almost two years later build correct vision to this issue:
1) don't use line
'images/avatar-pics/'.$this->user->username
in your behavoir - it throws a notice "Trying to get property of non-object" - good application doesn't thows notices and warnings.
2) all you need is use
'images/avatar-pics/' . CHtml::value($this, 'user.username')
instead. If $this->user is null, value method returns null, so be sure that you have related user to your model.
//inside the behavior:
$this->owner->user->username;
$this->owner - it's your model. Behavior is initialized before filling attributes, and the attribute value can be get only after the initialization.

Laravel 4: Unique(database) not validating

I am creating a basic CMS to teach myself the fundamentals of Laravel and PHP.
I have a 'pages' table and I am storing a url_title. I want this URL title to be unique for obvious reasons. However, whatever I do to validate it, fails. It just saves anyway. I'm sure it is something simple. Can you spot what is wrong with this code?
I am also using Former in the view, that doesn't validate either. I have tried hard-coding a value as the last option in the unique method and it fails also.
http://anahkiasen.github.io/former/
http://laravel.com/docs/validation#rule-unique
States: unique:table,column,except,idColumn
Here is my Controller:
public function store()
{
$validation = Pages::validate(Input::all());
if($validation->fails()) {
Former::withErrors($validation);
return View::make('myview');
} else {
Pages::create(array(
'title' => Input::get('title'),
'url_title' => Input::get('url_title'),
'status' => Input::get('status'),
'body' => Input::get('body'),
'seo_title' => Input::get('seo_title'),
'seo_description' => Input::get('seo_description')
));
//check which submit was clicked on
if(Input::get('save')) {
return Redirect::route('admin_pages')->with('message', 'Woo-hoo! page was created successfully!')->with('message_status', 'success');
}
elseif(Input::get('continue')) {
$id = $page->id;
return Redirect::route('admin_pages_edit', $id)->with('message', 'Woo-hoo! page was created successfully!')->with('message_status', 'success');
}
}
}
Here is my model:
class Pages extends Eloquent {
protected $guarded = array('id');
public static $rules = array(
'id' => 'unique:pages,url_title,{{$id}}'
);
public static function validate($data) {
return Validator::make($data, static::$rules);
}
}
I have tried the following:
public static $rules = array(
// 'id'=> 'unique:pages,url_title,{{$id}}'
// 'id'=> 'unique:pages,url_title,$id'
// 'id'=> 'unique:pages,url_title,:id'
// 'id'=> 'unique:pages,url_title,'. {{$id}}
// 'id'=> 'unique:pages,url_title,'. $id
);
Any ideas? I spoke to the guy who created Former. He can't make head nor tail about it either. He suggested tracking it back to find our what query Laravel uses to check the uniqueness and try running that directly in my DB to see what happens. I can't find the query to do this. Does anyone know where to track it down?
Many thanks
Your rule should be:
public static $rules = array(
'url_title' => 'unique:pages,url_title,{{$id}}'
);
As I guessed from your code Input::get('url_title')
You have to use the field name used in the form.
Thanks peeps. I have been using the Laravel unique solutions and it hasn't been working well. I found this package which solves the issue brilliantly.
https://github.com/cviebrock/eloquent-sluggable#eloquent
Definitely worth a look.
Thanks for your feedback.

Categories