creating a badge in the navbar and getting data from controller - php

I'm using laravel. I'm trying to create a badge in the navbar and getting the number of rows from a specific table in the database. I have the following codes for the navbar:
<span class='badge badge-pill badge-info'>
#php !empty(session('notifications.all2')) ? print(array_sum(session('notifications.all2'))) : ""
#endphp
</span>
and this for the controller:
class NotificationsController extends Controller
{
public function index ()
{
$settings = NotificationSettings::where('user_id', Auth::id())
->orderBy('name')
->get();
$user = User::where('id', auth::id())
->select('id')
->first();
if(count($settings) == 0)
{
$tasks = Tasks::all();
foreach ($tasks as $task)
{
NotificationSettings::create([
'user_id' => $user->id,
'name' => $task->name,
'module' => 'Task Schedule'
]);
$settings = NotificationSettings::where('user_id', Auth::id())
->orderBy('name')
->get();
}
}
$checkRestockTask = Tasks::where('name', 'Available Restock Inventory')->first();
if($checkRestockTask){
$checkUser = NotificationSettings::where('user_id', Auth::id())
->where('name', 'Available Restock Inventory')
->first();
if(!$checkUser){
NotificationSettings::create([
'user_id' => $user->id,
'name' => 'Available Restock Inventory',
'module' => 'Task Schedule'
]);
$settings = NotificationSettings::where('user_id', Auth::id())
->orderBy('name')
->get();
}
}
$data = [
'active' => 'settings',
'user_id' => $user->id,
'role' => $user->role_id ? $user->role_id : 'null',
'tasks' => $settings
]; //echo "<pre>"; print_r($data); echo "</pre>";
return view('notifications.index2')->with($data);
}
public function add ()
{
$data = array(
'active' => 'settings',
'user_id' => Auth::id(),
); //echo "<pre>"; print_r($data); echo "</pre>"; die();
return view('notifications.add')
->with($data);
}
public function saveNotification (Request $request)
{
$module = $request->get('module');
$user_id = $request->get('user_id');
$notification_name = $request->get('notification_name');
if($module == 1)
{
$module_name = 'Task Schedule';
}
$saved_notifs = NotificationSettings::where('user_id', $user_id)
->select('name')
->get();
$notif_names = array();
foreach ($saved_notifs as $saved_notif)
{
array_push($notif_names, $saved_notif->name);
}
if(in_array($notification_name, $notif_names))
{
return back()->with('error', 'Notification already added');
}
else
{
NotificationSettings::create([
'user_id' => $user_id,
'name' => $notification_name,
'module' => $module_name
]);
return redirect('notifications');
}
}
public function editNotification (Request $request, $user_id = null)
{
$checked_tasks = explode(',', $request->get('tasks'));
if(count($checked_tasks) > 0)
{
NotificationSettings::where('user_id', Auth::id())
->whereIn('name', $checked_tasks)
->update(['status' => 1]);
NotificationSettings::where('user_id', Auth::id())
->whereNotIn('name', $checked_tasks)
->update(['status' => 0]);
}
else
{
NotificationSettings::where('user_id', $user_id)
->update(['status' => 0]);
}
$settings = NotificationSettings::where('user_id', Auth::id())
->orderBy('name')
->get();
return json_encode($settings);
}
public function getTasks ()
{
$tasks = Tasks::select('name', 'id')
->orderBy('id')
->get();
$data = array(
'tasks' => $tasks,
); //echo "<pre>"; print_r($data); echo "</pre>"; die();
return $data;
}
public function viewAllNotifications ()
{
$user_id = Auth::id();
$view = Notification::where('recipient_id', $user_id)
->where('viewed', 0)
->update(['viewed' => 1]);
$notifications = Notification::where('recipient_id', $user_id)
->join('stores', 'stores.id', '=', 'notifications.store_id')
->select('notifications.content', 'notifications.recipient_id', 'notifications.url', 'notifications.read', 'notifications.viewed', 'stores.name', 'notifications.created_at', 'notifications.updated_at')
->orderBy('notifications.id', 'desc')
->paginate(25);
$data = array(
'active' => 'settings',
'notifications' => $notifications,
'user_id' => $user_id,
);
// return $data;
return view('notifications.all2')
->with($data);
}
public function getAllNotifications(Request $request){
$user_id = Auth::id();
$view = Notification::where('recipient_id', $user_id)
->where('viewed', 0)
->update(['viewed' => 1]);
$notifications = Notification::where('recipient_id', $user_id)
->join('stores', 'stores.id', '=', 'notifications.store_id')
->select('notifications.content', 'notifications.recipient_id', 'notifications.url', 'notifications.read', 'notifications.viewed', 'stores.name', 'notifications.created_at', 'notifications.updated_at')
->orderBy('notifications.id', 'desc')
->paginate(25);
return json_encode($notifications);
}
}
I just cant seem to get the number appear in the badge/pill that i have created. thanks for the answers in advance.

Related

How to ignore unique validation when updating fields in laravel8?

I currently use Laravel 8 and I want to know how do I ignore unique validation when a user is updating their profile? If the user is updating every field except the pageName I don't want it to throw a vaildation error cause the user is already the owner of that pageName. I tried this code but it gives error: ErrorException
Undefined variable: user
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name'.$user->id,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
This is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Auth;
use DB;
use App\Models\User;
use App\Models\Button;
use App\Models\Link;
class UserController extends Controller
{
//Statistics of the number of clicks and links
public function index()
{
$userId = Auth::user()->id;
$littlelink_name = Auth::user()->littlelink_name;
$links = Link::where('user_id', $userId)->select('link')->count();
$clicks = Link::where('user_id', $userId)->sum('click_number');
return view('studio/index', ['littlelink_name' => $littlelink_name, 'links' => $links, 'clicks' => $clicks]);
}
//Show littlelink page. example => http://127.0.0.1:8000/+admin
public function littlelink(request $request)
{
$littlelink_name = $request->littlelink;
$id = User::select('id')->where('littlelink_name', $littlelink_name)->value('id');
if (empty($id)) {
return abort(404);
}
$information = User::select('littlelink_name', 'littlelink_color', 'littlelink_fontcolor', 'littlelink_pixiv', 'littlelink_description')->where('id', $id)->get();
$links = DB::table('links')->join('buttons', 'buttons.id', '=', 'links.button_id')->select('links.link', 'links.id', 'buttons.name')->where('user_id', $id)->orderBy('up_link', 'asc')->get();
return view('littlelink', ['information' => $information, 'links' => $links, 'littlelink_name' => $littlelink_name]);
}
//Show buttons for add link
public function showButtons()
{
$data['buttons'] = Button::select('name')->get();
return view('studio/add-link', $data);
}
//Save add link
public function addLink(request $request)
{
$request->validate([
'link' => 'required|url',
'button' => 'required'
]);
$link = $request->link;
$button = $request->button;
$userId = Auth::user()->id;
$buttonId = Button::select('id')->where('name' , $button)->value('id');
$links = new Link;
$links->link = $link;
$links->user_id = $userId;
$links->button_id = $buttonId;
$links->save();
return back()->with('message', 'Link Added');
}
//Count the number of clicks and redirect to link
public function clickNumber(request $request)
{
$link = $request->link;
$linkId = $request->id;
if(empty($link && $linkId))
{
return abort(404);
}
Link::where('id', $linkId)->increment('click_number', 1);
return redirect()->away($link);
}
//Show link, click number, up link in links page
public function showLinks()
{
$userId = Auth::user()->id;
$data['links'] = Link::select('id', 'link', 'click_number', 'up_link')->where('user_id', $userId)->orderBy('created_at', 'desc')->paginate(10);
return view('studio/links', $data);
}
//Delete link
public function deleteLink(request $request)
{
$linkId = $request->id;
Link::where('id', $linkId)->delete();
return back();
}
//Raise link on the littlelink page
public function upLink(request $request)
{
$linkId = $request->id;
$upLink = $request->up;
if($upLink == 'yes'){
$up = 'no';
}elseif($upLink == 'no'){
$up = 'yes';
}
Link::where('id', $linkId)->update(['up_link' => $up]);
return back();
}
//Show link to edit
public function showLink(request $request)
{
$linkId = $request->id;
$link = Link::where('id', $linkId)->value('link');
$buttons = Button::select('name')->get();
return view('studio/edit-link', ['buttons' => $buttons, 'link' => $link, 'id' => $linkId]);
}
//Save edit link
public function editLink(request $request)
{
$request->validate([
'link' => 'required|url',
'button' => 'required',
]);
$link = $request->link;
$button = $request->button;
$linkId = $request->id;
$buttonId = Button::select('id')->where('name' , $button)->value('id');
Link::where('id', $linkId)->update(['link' => $link, 'button_id' => $buttonId]);
return redirect('/studio/links');
}
//Show littlelinke page for edit
public function showPage(request $request)
{
$userId = Auth::user()->id;
$data['pages'] = User::where('id', $userId)->select('littlelink_name', 'littlelink_color', 'littlelink_fontcolor', 'littlelink_pixiv', 'littlelink_description')->get();
return view('/studio/page', $data);
}
//Save littlelink page (name, description, logo)
public function editPage(request $request)
{
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name'.$user->id,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
$userId = Auth::user()->id;
$littlelink_name = Auth::user()->littlelink_name;
$profilePhoto = $request->file('image');
$pageName = $request->pageName;
$pageColor = $request->pageColor;
$pageFontcolor = $request->pageFontcolor;
$pageDescription = $request->pageDescription;
$pagePixiv = $request->pagePixiv;
User::where('id', $userId)->update(['littlelink_name' => $pageName, 'littlelink_color' => $pageColor, 'littlelink_fontcolor' => $pageFontcolor, 'littlelink_pixiv' => $pagePixiv, 'littlelink_description' => $pageDescription]);
if(!empty($profilePhoto)){
$profilePhoto->move(public_path('/img'), $littlelink_name . ".png");
}
return back()->with('message', 'Saved');
}
//Show user (name, email, password)
public function showProfile()
{
$userId = Auth::user()->id;
$data['profile'] = User::where('id', $userId)->select('name', 'email')->get();
return view('/studio/profile', $data);
}
//Save user (name, email, password)
public function editProfile(request $request)
{
$request->validate([
'name' => 'required|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|min:8',
]);
$userId = Auth::user()->id;
$name = $request->name;
$email = $request->email;
$password = Hash::make($request->password);
User::where('id', $userId)->update(['name' => $name, 'email' => $email, 'password' => $password]);
return back();
}
}
Anyone know how to fix this?
You can change your code to the following
$userId = Auth::user()->id;
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name,'.$userId,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
you can use the Rule object to make that validation:
'pageName' => ['nullable','alpha_dash', Rule::unique('users','littlelink_name')->ignore($user->id)

Cakephp Error: The Categories association is not defined on Carts

You can see I have used $this->loadModel('Categories'); in my Cart controller function.
public function home($cat_id=null, $subcat_id=null)
{
// Set leftmenu
$this->loadModel('Categories');
$query = $this->Categories->find('all', [
'contain' => ['SubCategories']
]);
$this->set('categories', $query);
// Set conditions
$conditions = array();
if (!empty($cat_id)) {
$conditions['Products.category_id'] = $cat_id;
}
if (!empty($subcat_id)) {
$conditions['Products.sub_category_id'] = $subcat_id;
}
$this->paginate = [
'conditions' => $conditions,
'contain' => ['Categories', 'SubCategories', 'Discounts' => function ($q) {
return $q
->where(['Discounts.start_at <' => date('Y-m-d H:i:s'), 'Discounts.end_at >' => date('Y-m-d H:i:s')])
->limit(1);
}]
];
$this->set('products', $this->paginate($this->Products));
$this->set('_serialize', ['products']);
}
When I add the items in the cart and click the cart button to view the items then I get this error.

Lumen count(): Parameter must be an array or an object that implements Countable

I tried creating a multiple image upload along with a post, but I constantly get an error on count function when I try to count the elements in the array. For the single image, the code works fine if I remove that array and counts. Lumen latest version, PHP version 7.3 but I downgraded it to 7.1.
Code:
<?php
class PostController extends Controller {
public function __construct() {
$this->middleware('auth');
}
public function index() {
return Auth::user()->post;
}
public function show($post_id) {
$post = Post::findOrFail($post_id);
if (Auth::user()->id !== $post->user_id) {
return response()
->json(['status' => 'error', 'message' => 'unauthorized'], 401);
}
return $post;
}
public function store(Request $request) {
$post = new Post;
$post->setConnection('mysql1');
$user = User::where('token', $request->token)
->first();
if ($user) {
$post1 = $post->create(['post_id' => rand() , 'title' => $request->title, 'cooked_time' => $request->cooked_time, 'user_id' => $request->token, 'location' => $user['name'], 'dispose_time' => strtotime('+01 hours', strtotime($request->cooked_time)) , 'food_type' => $request->food_type, 'description' => $request->description, 'serve_quantity' => $request->serve_quantity, 'lat' => $request->lat, 'long' => $request->long, ]);
$post = Post::where('user_id', $request->token)
->orderBy('id', 'DESC',)
->limit('1')
->get();
if ($request->hasFile('image')) {
// $image_array = [];
$image_array = $request->file('image');
$array_len = count($image_array);
for ($i = 0;$i < $array_len;$i++) {
$image_size = $image_array[$i]->getClientSize();
$image_ext = $image_array[$i]->getClientOriginalExtension();
$new_image_name = rand(123456, 99999999) . "." . $image_ext;
if (!function_exists('public_path')) {
/**
* Return the path to public dir
*
* #param null $path
*
* #return string
*/
function public_path($path = null) {
return rtrim(app()->basePath('public/' . $path) , '/');
}
}
$destination_path = public_path('/images');
$image_array[$i]->move($destination_path, $new_image_name);
$image = new PostImage;
$images->image_name = $new_image_name;
$images->post_id = $post1['post_id'];
$images->save();
}
}
return response()
->json(['message' => 'success', 'user' => $user['name'], 'post' => $post1, ], 200);
}
}
public function update(Request $request, $post_id) {
$post = Board::find($post_id);
if (Auth::user()->id !== $post_id->user_id) {
return response()
->json(['status' => 'error', 'message' => 'unauthorized'], 401);
}
$post->update($request->all());
return response()
->json(['status' => 'success', 'post' => $post], 200);
}
public function destroy($id) {
$post = Post::find($post_id);
if (Auth::user()->id !== $post->user_id) {
return response()
->json(['status' => 'error', 'message' => 'unauthorized'], 401);
}
if (Post::destroy($id)) {
return response()->json(['status' => 'success', 'message' => 'Post Deleted Successfully'], 200);
}
return response()
->json(['status' => 'error', 'message' => 'Something Went Wrong']);
}
}
http://php.net/manual/en/migration72.incompatible.php#migration72.incompatible.warn-on-non-countable-types
Try to change
count($image_array)
To
count((is_countable($image_array)?$image_array:[]))
And use this trick for all count() calls

add orderBy ('created_at', 'desc') to my account

I would like to create an orderBy ('created_at', 'desc') and paginate, for my articles posted in my account, here is my code.
MyaccountController
public function viewProfile($username) {
if($username) {
$user = User::where('username', $username)->firstOrFail();
} else {
$user = User::find(Auth::user()->id);
}
return view('site.user.account', [
'user' => $user,
'events' => $user->events,
'articles' => $user->articles,
]);
}
Assuming the relationship is correct on the User model:
'articles' => $user->articles()->orderByDesc('created_at')->paginate()

Converting Array to String Codeigniter 3.0

I am trying to insert an element into my 'category' table and use the inserted element's id to insert another element into my 'subcategory' table.
This is my code in my controller
public function insertCategory(){
$category = $this->input->post('category');
$subcategory = $this->input->post('subcategory');
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('subcategory', 'Subcategory', 'required');
if($this->form_validation->run() == FALSE){
$this->load->view('ADMIN_ADDCategory');
}
else{
$category_id = $this->admin_model->insertCategory($category);
$this->admin_model->insertSubcategory($category_id, $subcategory);
}
}
And this is my code in my model
function insertCategory($category){
$data = array(
'category' => $category,
'status' => 1
);
$this->db->insert('category', $data);
$this->db->select('id');
$this->db->from('category');
$this->db->where('category', $category);
$this->db->limit(1);
$query = $this->db->get();
return $query->result();
}
function insertSubcategory($category_id, $subcategory){
$data = array(
'category_id' => $category_id,
'subcategory' => $subcategory,
'status' => 1
);
$this->db->insert('subcategory', $data);
}
However I am getting this error
I already tried using $category_id = (array) $this->admin_model->insertCategory($category); but it still doesn't work
How do I overcome this error? Thank you for the help.
$this->admin_model->insertSubcategory($category_id, $subcategory);
$category_id is an array , so , you must do it like this:
$this->admin_model->insertSubcategory($category_id[0]->field, $subcategory);
You should try this
$this->admin_model->insertSubcategory($category_id[0]->id;, $subcategory);
try this code
Model
public function insert($table, $data)
{
if($this->db->insert($table,array $data))
{
return $this->db->insert_id();
}else
return false
}
controller
public function insertCategory(){
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('subcategory', 'Subcategory', 'required');
if($this->form_validation->run() == FALSE){
$this->load->view('ADMIN_ADDCategory');
}
else{
$category = $this->input->post('category');
$subcategory = $this->input->post('subcategory');
//data must be an array
$data = [
'category' => $category,
'status' => '1'
];
$category_id = $this->admin_model->insert('tablename',$data)
if($category_id != false)
{
$data = [
'category_id' => $category_id,
'subcategory' => $subcategory,
'status' => 1
];
if($this->admin_model->insert('table name', $data) != false)
{
echo 'success';
//or load your success page
}else{
echo 'failed';
//or load your success page
}
}else{
echo 'failed';
//or load your success page
}
}
}

Categories