dimanche 16 mai 2021

Laravel 8: Redirecting Forbidden Users To Their Respective Home Pages

Good Day

I'm new to laravel, and I'm building a website that has multiple users (Student, Supervisor, HOD). I am making use of the laratrust package to manage my users. If a student tries to access a url belonging to a supervisor, for example, laratrust throws an exception that says "USER DOES NOT HAVE ANY OF THE NECESSARY ACCESS RIGHTS". I would like to redirect the student back to their home page instead of this exception.

Here are my routes:

web.php

// Routes For Students
Route::group([
    'name' => 'student.',
    'prefix' => 'student',
    'namespace' => 'App\Http\Controllers',
    'middleware' => ['auth', 'role:student']
], function () {
    Route::get('home', 'StudentController@index')->name('student-home');
    Route::get('proposal', 'StudentController@proposal')->name('student-proposal');
    Route::get('thesis', 'StudentController@thesis')->name('student-thesis');
});

// Routes For Supervisors
Route::group([
    'name' => 'supervisor.',
    'prefix' => 'supervisor',
    'namespace' => 'App\Http\Controllers',
    'middleware' => ['auth', 'role:supervisor']
], function () {
    Route::get('home', 'supervisorController@index')->name('supervisor-home');
    Route::get('proposal', 'supervisorController@proposal')->name('supervisor-proposal');
    Route::get('thesis', 'supervisorController@thesis')->name('supervisor-thesis');
});

// Routes For HOD
Route::group([
    'name' => 'hod.',
    'prefix' => 'hod',
    'namespace' => 'App\Http\Controllers',
    'middleware' => ['auth', 'role:hod']
], function () {
    Route::get('home', 'hodController@index')->name('hod-home');
    Route::get('proposal', 'hodController@proposal')->name('hod-proposal');
    Route::get('thesis', 'hodController@thesis')->name('hod-thesis');
});

I have researched that in order to do this, I need to edit this specific part of the laratrust.php file:

    'middleware' => [

        'register' => true,

        'handling' => 'abort', // This needs to change to redirect

        'handlers' => [
            /**
             * Aborts the execution with a 403 code and allows you to provide the response text
             */
            'abort' => [
                'code' => 403,
                'message' => 'User does not have any of the necessary access rights.'
            ],

            // Redirect User To Their Respective Home Based On Their Role.
            'redirect' => [
                'url' => '/home',
                'message' => [
                    'key' => 'error',
                    'content' => ''
                ]
            ]
        ]
    ],

The home url is different based on the user type, so I want to know how I can check determine the type of user, then based on that assign their respective home url. Please let me know if you require more code or better explanation.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3yhlltZ
via IFTTT

Return top 3 grouped results from relationship

I have a table, comments, that looks like this:

+====+=========+
| id | message |
+====+=========+
|  1 |      Hi |
|  2 |   World |
+====+=========+

I have a second table, comment_stats, which keeps track of the total number of votes on each comment, that looks like this:

+====+============+=======+
| id | comment_id | votes |
+====+============+=======+
|  1 |          1 |    10 |
|  2 |          2 |     0 |
+====+============+=======+

And lastly, I have a third table, comment_votes, which keeps track of each individual user's vote for each comment, that looks like this:

+====+============+=========+=========+
| id | comment_id | user_id |    type |
+====+============+=========+=========+
|  1 |          1 |      10 |       0 |
|  2 |          1 |       9 |       0 |
|  3 |          1 |       8 |       1 |
|  4 |          1 |       7 |       2 |
|  5 |          1 |       6 |       1 |
|  6 |          1 |       5 |       5 |
|  7 |          1 |       4 |       3 |
|  8 |          1 |       3 |       3 |
|  9 |          1 |       2 |       1 |
| 10 |          1 |       1 |       0 |
+====+============+=========+=========+

As you can see, each comment can be voted on by other users (comment_votes) and the total votes are kept track of in comment_stats. Each vote has a type. There are a total of 6 possible types (0-5).

My current Comment.php class looks like:

class Comment extends Model
{
    protected $with = [
        'votes', 'stats'
    ];

    public function votes()
    {
        return $this->hasMany('App\Vote');
    }

    public function stats()
    {
        return $this->hasOne('App\Stat');
    }
}

My Stat.php class looks like:

class Stat extends Model
{
    protected $with = [
        'topTypes'
    ];

    public function comment()
    {
        return $this->belongsTo('App\Comment');
    }

    public function topTypes()
    {
        // Need to return an array of the top 3 types here
    }
}

And my Vote.php class looks like:

class Vote extends Model
{
    public function comment()
    {
        return $this->belongsTo('App\Comment');
    }
}

I'd like to retrieve the top 3 types for each comment. So for comment_id = 1, the output would be [0, 1, 3] (as an array), in that order. 0 appears 3 times, 1 appears 3 times, and 3 appears twice. If there is a tie, it should get the lower integer type.

I'm trying to get the JSON to end up looking something like this, so that the top_types is part of stats:

{
    "id": 1,
    "message": "Hi",
    "stats": {
        "id": 1,
        "comment_id": 1,
        "votes": 10,
        "top_types": [0, 1, 3]
    }
}

How could I achieve this? All of these relationships are driving me insane.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3yi4Wpt
via IFTTT

i need pagination with sortBy in laravel

I have 3 tables products, prices, cats.

I need to filter product by cats and sort by price but I have a problem:

this code work very well but needs pagination.

$products = Product::with('photo', 'price', 'brand')
    ->whereHas('cats', function ($q) use ($cat) {
        $q->where('cat_id', $cat->id);
    })
    ->get()
    ->sortByDesc(function($query) {
        return $query->price->price;
    });

at first I did it like this:

$products = Product::with('photo', 'price', 'brand')
    ->whereHas('cats', function ($q) use ($cat) {
        $q->where('cat_id', $cat->id);
    })
    ->paginate($page)
    ->sortByDesc(function ($query) {
        return $query->price->price;
    });

but links() did not work.

After i did it like this:

$products = Product::with('photo', 'price', 'brand')
    ->whereHas('cats', function ($q) use ($cat){
        $q->where('cat_id', $cat->id);
    })
    ->paginate($page);

$products->setCollection(
    $products->sortBy(function ($query) {
        return $query->price->id;
    })
);

but sortBy does not work.

so I can't use orderBy() by join prices table

because when I do it I can show all products and I can't filter product by categories

my mind does not work, if someone can to help me, I will be very grateful



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3tW7ciC
via IFTTT

I always get this error Trying to get property 'nama_lengkap' of non-object

index.blade.php

                <td class="sorting_1" style=""></td>
                <td></td>

TicketController

 public function index(Request $request)
    {
        $data = Ticket::with('User','Kategori','Prioritas','Status')->when($request->keyword, function ($query) use ($request) 
        {
            $query->where('judul', 'like', "%{$request->keyword}%");
            })->paginate(5); 
            $data->appends($request->only('keyword'));

            
            return view('admin.crud_ticket.index', compact('data'));         
        }

model Ticket

public function user()
    {
        return $this->belongsTo(User::class);
    }

model User

public function ticket()
    {
        return $this->hasMany(Ticket::class);
    }

if you have a solution to the problem that i am experiencing please help me



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3wde9gD
via IFTTT

PHP small api based task

I want to perform small task like when you search for a vendor and in your area within the range of 1km it will show 10 vendors and if 2 of these will change a place then it will show only 8 vendors and while other 2 added another place so whole these things I want to perform in PHP and used API for tracking purpose and I want to use tower tracker for tracking so how I can I do this so anyone can suggest me for this



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3yf7dla
via IFTTT

How to send array variable in laravel mail template?

$carts= Cart::leftjoin('products', 'products.id', '=', 'carts.productid')
    ->leftjoin('sellers', 'sellers.id', '=', 'products.seller')
    ->select('products.*','carts.productid as productid','carts.userid as userid','carts.quantity as cartquantity','carts.subtotal as subtotal','carts.id as cartid','sellers.id as sellerid')->where('carts.userid',$_SESSION['salmonlightsuserid'])->get();
$data1 = array('carts'=>"$carts",'subtotal'=>"$subtotal",'totalquantity'=>"$totalquantity",'primaryaddress'=>"$primaryaddress");
    $useremail=$_SESSION['salmonlightsuseremail'];

     Mail::send('order-email-template',$data1, function($message) use($useremail){
     $message->to($useremail)->subject
         ('Order');
     $message->from('noreply@gamil.com');
     });

It gives error in order-email-template.blade.php Error is:- Invalid argument supplied for foreach() @foreach($carts as $cartsnew)



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3yh6FeH
via IFTTT

How do I convert my submitted form uploads as one pdf and send that as an attachment to receiver in laravel?

A Laravel 5.7 project

I have a form where I need to upload 3 images and 2 pdfs in single form.

What I am going for:

  1. Submit the form and save data.
  2. Convert the files uploaded via the user form as a single pdf.
  3. Sending the converted pdf as a mail attachment using code.

Tried like this

public function sendmail(Request $request){
        $data["email"]=$request->get("email");
        $data["client_name"]=$request->get("client_name");
        $data["subject"]=$request->get("subject");

        $pdf = PDF::loadView('mails.mail', $data);

        try{
            Mail::send('mails.mail', $data, function($message)use($data,$pdf) {
            $message->to($data["email"], $data["client_name"])
            ->subject($data["subject"])
            ->attachData($pdf->output(), "invoice.pdf");
            });
        }catch(JWTException $exception){
            $this->serverstatuscode = "0";
            $this->serverstatusdes = $exception->getMessage();
        }
        if (Mail::failures()) {
             $this->statusdesc  =   "Error sending mail";
             $this->statuscode  =   "0";

        }else{

           $this->statusdesc  =   "Message sent Succesfully";
           $this->statuscode  =   "1";
        }
        return response()->json(compact('this'));
 }


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3fl56DH
via IFTTT