In my controller I retrieve a list of messages from the message model. I am trying to add a filter, but the filters are cancelling each other out.
// Controller
public function __construct(Message $messages)
{
$this->messages = $messages;
}
public function index($filter = null)
{
$messages = $this->messages
->actioned($filter == 'actioned' ? false : true)
->ignored($filter == 'ignored' ? true : false)
->get();
return view('...
}
// Model
public function scopeActioned($query, $actioned = true)
{
$constraint = ($actioned ? 'whereNotNull' : 'whereNull');
return $query->$constraint('ts_actioned');
}
public function scopeIgnored($query, $ignored = true)
{
return $query->where('is_ignored', ($ignored ? 'Yes' : 'No'));
}
How can I setup Eloquent so that scopeActioned is only called if $filter is set to 'actioned', and the same for ignored?
Simple Approach:
public function index($filter = null)
{
$query = $this->messages->query();
//applying filter
if($filter == 'actioned') {
$query->actioned();
}
if($filter == 'ignored') {
$query->ignored();
}
$messages = $query->get();
return view('...
}
Another Approach is work in Scope Function.
// Model
public function scopeActioned($query, $actioned = true)
{
if($actioned) {
$query->whereNotNull('ts_actioned');
}
return $query;
}
public function scopeIgnored($query, $ignored = true)
{
if($ignored) {
$query->where('is_ignored', 'Yes');
}
return $query;
}
Related
The two tables tbl_product_manager and tbl_tags with many to many relations. I used eloquent to to make a relations between the corresponding models. I am able to to insert the data in these two table but the problem is the pivot table is not updated correspondingly.
Controller.php:
public function addProduct()
{
$rules = array('product_name' => 'required',
'product_url' => 'required');
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Some fields are missing');
return View::make('admin.product.add');
}
else {
$productName = Input::get('product_name');
$productUrl = Input::get('product_url');
$productUrl = preg_replace('/[^A-Za-z0-9\-]/', '', $productUrl);
$productExist = ProductManagementModel::checkExist($productUrl);
if( count($productExist)!=0) {
$message = 'product <b>'.$productName.'</b> with url <b>'.$productUrl.'</b> is already exist';
Session::flash('class', 'alert alert-error');
Session::flash('message', $message);
return View::make('admin.product.add');
}
else {
$imageFile = Input::file('userfile');
$destinationPath = 'uploads/products/';
$rEFileTypes = "/^\.(jpg|jpeg|gif|png){1}$/i";
$maximum_filesize = 1 * 1024 * 1024;
if($imageFile) {
$filename = $imageFile->getClientOriginalName();
$extension = strrchr($filename, '.');
$size = $imageFile->getSize();
$new_image_name = "products" . "_" . time();
if ($size <= $maximum_filesize && preg_match($rEFileTypes, $extension)) {
$attachment = $imageFile->move($destinationPath, $new_image_name.$extension);
} else if (preg_match($rEFileTypes, $extension) == false) {
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Warning : Invalid Image File!');
return View::make('admin.product_management.add');
} else if ($size > $maximum_filesize) {
Session::flash('class', 'alert alert-error');
Session::flash('message', "Warning : The size of the image shouldn't be more than 1MB!");
return View::make('admin.product_management.add');
}
}
$logo = isset($attachment) ? $new_image_name . $extension : NULL;
$objectProduct = new ProductManagementModel;
$objectProduct->product_name = Input::get('product_name');
$objectProduct->product_url = $productUrl;
$objectProduct->category_id = Input::get('category_id');
$objectProduct->product_cost = Input::get('product_cost');
$objectProduct->product_short_description = Input::get('product_short_description');
$objectProduct->product_description = Input::get('product_description');
$objectProduct->is_active = Input::get('is_active');
$objectProduct->created_at = Auth::user()->id;
$objectProduct->updated_at = Auth::user()->id;
if($logo != '')
{
$objectProduct->product_attachment = $logo;
}
$objectTags = new TagModel;
$objectTags->size_id = Input::get('size_id');
$objectTags->brand_id = Input::get('brand_id');
$objectTags->color_id = Input::get('color_id');
$objectTags->food_id = Input::get('food_id');
$objectTags->save();
//$tag = new TagModel::all();
$objectProduct->save();
if(isset($request->tags)) {
$post->Tags()->sync($request->tags, false);
}
if($objectProduct->id) {
Session::flash('class', 'alert alert-success');
Session::flash('message', 'Product successfully added');
return View::make('admin.product_management.add');
} else {
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Something error');
return View::make('admin.product_management.add');
}
}
}
}
ProductManagementModel.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class ProductManagementModel extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'product_manager';
public function Tags(){
return $this->belongsToMany('TagModel', 'product_tag', 'product_id', 'tag_id');
}
public function Categories(){
return $this->hasOne('CategoriesModel', 'id');
}
public static function getAllProducts(){
return $products = ProductManagementModel::with('categories','tags')->get();
}
public static function checkExist($url)
{
return $products = DB::table('product_manager')
->where('is_deleted', 0)
->where('product_url', $url)
->first();
}
}
TagModel.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class TagModel extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'tag';
public function ProductManagents() {
return $this->belongsToMany('ProductManagentModel');
}
public function Color(){
return $this->hasOne('ColorModel', 'color_id');
}
public function Brand() {
return $this->hasOne('BrandproModel','brand_id');
}
public function size() {
return $this->hasOne('SizeModel','size_id');
}
public function food() {
return $this->hasOne('FoodModel','food_id');
}
}
During my research i found that using sync function will be appropriate to updated the pivot table. But I failed to use it.
I am expecting to resolve this problem or something new way to find out the solution.
Thanks in advance.
Look at attach, detach or synch method :
https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships
Note it's more easily if you respect the eloquent naming convention
http://www.rappasoft.com/articles/laravel-eloquent-naming-convention-guide/
I am trying to print a controller method's result on view but it is giving me an error:
Undefined variable: $states. Can someone help me to point out what is wrong in my code?
Model code:
public function state_names() {
$query = $this->db->select('name')
->get('place')
->where('parent','India');
$query->db->get();
return $query->result();
}
Controller Code:
public function state_names() {
$st['states'] = $this->place_model->state_names();
if ($this->form_validation->run('resource_signup') == TRUE) {
if (isset($st['states']) && $st['states']->num_rows() > 0) {
$this->load->view('/web/resource_signup',$st);
}
}
return array();
}
View code:
<?php foreach ($states as $state) {
echo $state->name;
}
try this one
public function state_names() {
$this->db->select('name')
$this->db->get('place')
$this->db->where('parent','India');
$query=$this->db->get();
return $query->result_array();
}
In your model you are running query twice - for each method get(). You should run it once:
public function state_names() {
$query = $this->db->select('name')
->where('parent','India')
->get('place');
return $query->result();
}
In your controller you can't check num_rows() because there are results - not full response from database.
public function state_names() {
$st['states'] = $this->place_model->state_names();
if ($this->form_validation->run('resource_signup') == TRUE) {
if (isset($st['states'])) {
$this->load->view('/web/resource_signup',$st);
}
}
return array();
}
Your Problem is 2 place First in Model and second in controller
if (isset($st['states']) && $st['states']->num_rows() > 0)
and Model
Model Solution
public function state_names() {
$query = $this->db->select('name')
->where('parent','India')
->get('place');
// $query->db->get();
if($query->num_rows() > 0){
return $query->result();
}
}
N.B [ Here Where will be first and get will be last its good practice ];
Controller Solution :
public function state_names() {
$st['states'] = $this->place_model->state_names();
if ($this->form_validation->run('resource_signup') == TRUE) {
if (isset($st['states']) ) {
$this->load->view('/web/resource_signup',$st);
}
}
return array();
}`
I currently have a relationship between checklistItem and actions as followed:
public function action()
{
return $this->belongsTo(Action::class, 'action_id', 'id');
}
public function checklistItem()
{
return $this->hasOne(ChecklistItem::class, 'action_id', 'id');
}
I currently made a method, when saving an action, the checklistItem status should also change depending on what was chosen:
public static function saveFromRequest(Request $request)
{
if (($action = parent::saveFromRequest($request)) !== null){
if (!is_null($action->checklistItem)) {
$action->checklistItem->value->status = $action->switchStatusChecklist($action);
//Need to update or save this specific checklistItem
$action->checklistItem->save();
}
}
return $action;
}
function switchStatusChecklist($action)
{
switch($action->status) {
case 'closed':
$status = 'checked';
break;
case 'canceled':
$status = 'notapplicable';
break;
default:
$status = 'open';
break;
}
return $status;
}
Problem:
My checklistitem does not get updated.
i have a controller function that needs to be redirected to a route with a different function to avoid redundancy of codes. is it possible to put a redirect to a different function?
Here is the code:
public function index()
{
$x = Auth::user()->id;
$id = DB::table('requests')->where('id', $x)->lists('userid');
if (!is_null($id)) {
$frnd = DB::table('users')->whereIn('id', $id)->get();
if (!is_null($frnd)) {
return view('friendlist', compact('frnd'));
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
}
public function respond()
{
$frnds = new Friend;
$id = Auth::user()->id;
$friendid = Request::input('friendid');
$frnds->id = $id;
$frnds->friendid = $friendid;
if (Input::get('accept')) {
$frnds->save();
}
DB::table('requests')->where('id', $id)->where('userid', $friendid)
return // this is where i should redirect to page with function index()
}
Name the index route in routes definition like this
Route::get('home', ['uses' => 'YourController#index', 'as' => 'home']);
Then use redirect method to redirect to this route:
return redirect()->route('home');
For more info on redirects use official docs
http://laravel.com/docs/5.1/responses#redirects
I don't think is a perfect, but someone prefer this way:
private function _index()
{
$x = Auth::user()->id;
$id = DB::table('requests')->where('id', $x)->lists('userid');
if (!is_null($id)) {
$frnd = DB::table('users')->whereIn('id', $id)->get();
if (!is_null($frnd)) {
return view('friendlist', compact('frnd'));
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
}
public function index()
{
$this->_index();
}
public function respond()
{
$frnds = new Friend;
$id = Auth::user()->id;
$friendid = Request::input('friendid');
$frnds->id = $id;
$frnds->friendid = $friendid;
if (Input::get('accept')) {
$frnds->save();
}
DB::table('requests')->where('id', $id)->where('userid', $friendid)
$this->_index();
}
private function for repeated code.
I have just created a library class in laravel.
class Message {
public static $data = array();
public function __construct() {
// If session has flash data then set it to the data property
if (Session::has('_messages')) {
self::$data = Session::flash('_messages');
}
}
public static function set($type, $message, $flash = false) {
$data = array();
// Set the message properties to array
$data['type'] = $type;
$data['message'] = $message;
// If the message is a flash message
if ($flash == true) {
Session::flash('_messages', $data);
} else {
self::$data = $data;
}
}
public static function get() {
// If the data property is set
if (count(self::$data)) {
$data = self::$data;
// Get the correct view for the message type
if ($data['type'] == 'success') {
$view = 'success';
} elseif ($data['type'] == 'info') {
$view = 'info';
} elseif ($data['type'] == 'warning') {
$view = 'warning';
} elseif ($data['type'] == 'danger') {
$view = 'danger';
} else {
// Default view
$view = 'info';
}
// Return the view
$content['body'] = $data['message'];
return View::make("alerts.{$view}", $content);
}
}
}
I can use this class in my views calling Message::get(). In the controllers, I can set the message as Message::set('info', 'success message here.'); and it works perfectly fine.
However, I can not use this class for flash messages redirects using Message::set('info', 'success message here.', true). Any idea, whats wrong in this code?
First problem is the constructor function is not called when using the above get and set methods, with minor modification the code is now working. :)
class Message {
public static $data = array();
public static function set($type, $message, $flash = false) {
$data = array();
// Set the message properties to array
$data['type'] = $type;
$data['message'] = $message;
// If the message is a flash message
if ($flash == true) {
Session::flash('_messages', $data);
} else {
self::$data = $data;
}
}
public static function get() {
// Check the session if message is available in session
if (Session::has('_messages')) {
self::$data = Session::get('_messages');
}
// If the data property is set
if (count(self::$data)) {
$data = self::$data;
// Get the correct view for the message type
if ($data['type'] == 'success') {
$view = 'success';
} elseif ($data['type'] == 'info') {
$view = 'info';
} elseif ($data['type'] == 'warning') {
$view = 'warning';
} elseif ($data['type'] == 'danger') {
$view = 'danger';
} else {
// Default view
$view = 'info';
}
// Return the view
$content['body'] = $data['message'];
return View::make("alerts.{$view}", $content);
}
}
}