laravel,laravel-4,routing,models,relationships , Best way of protecting the show() method against users accessing other users messages


Best way of protecting the show() method against users accessing other users messages

Question:

Tag: laravel,laravel-4,routing,models,relationships

Ok, so I have a basic messaging system, I have a relationship set up so I can just call $user->messages to retrieve an array of the users inbox messages. I also have a very simple show method that currently only grabs the message with id passed to the show() function.

The question is what would be the best way to protect that messages/2 URL so a user couldn't just type any number in the URL and access another users messages.

Should I use a route filter and basically run another query to ensure the message id is accessible by the user or is there something I can do with the relationship, perhaps check the id against the messages array and if it exists then the user must have access?

public function up()
    {
        Schema::create('messages', function(Blueprint $table) {
            $table->increments('id');
            $table->mediumText('subject');
            $table->text('message');
            $table->boolean('draft');
            $table->integer('sender_id')->unsigned();
            $table->softDeletes();
            $table->timestamps();

            $table->foreign('sender_id')->references('id')->on('users')->onUpdate('cascade');
        });

        Schema::create('message_assets', function(Blueprint $table) {
            $table->increments('id');
            $table->integer('message_id')->unsigned();
            $table->string('filename', 255);
            $table->softDeletes();

            $table->foreign('message_id')->references('id')->on('messages')->onUpdate('cascade');
        });

        Schema::create('message_users', function(Blueprint $table) {
            $table->increments('id');
            $table->integer('message_id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->integer('read')->default(0);
            $table->string('folder', 255)->nullable();
            $table->softDeletes();

            $table->foreign('message_id')->references('id')->on('messages')->onUpdate('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade');
        });
    }

Answer:

in the simplest form, in your MessagesController in the show method, you can add an additional parameter to your query and get the record where message_id = the paramater from the url and the user_id on that message is the authenticated user's ID.... do something like

$message = App\Message::where('id', '=', $id)
                      ->where('user_id', '=', Auth::user()->id)
                      ->first();

if you are doing a more advanced design and have a MessageRepository, this logic could be extracted there so in your controller you do something like

$this->repository->getById($id);

and in the messages repository the getById() method would do something similar to the above code example using an eloquent model. this method allows the controller to be clean and the logic to be re-used elsewhere in the app if needed

ADDED to work with the pivot table specified above. this will only work for a user that has the message in the inbox:

DB::table('messages')
    ->join('message_users', 'messages.id', '=', 'message_users.message_id')
    ->where('message_users.message_id', $id)
    ->where('message_users.user_id', $userId)
    ->where('message_users.deleted_at', null)
    ->select('messages.*')
    ->first();

Related:


custom orderBy() on constraining eager loads?


laravel,eager-loading
my question is about the possibilty of customizing Laravel's orderBy() method of the query builder, which i am using to sort an eager loaded dataset. This is the query scope I am using to generate the dataset. Everything works fine so far with this. public function scopeRestaurantsWithMenusToday($query, $city_uri){ return $query->where('city_uri',...

Sync element to a child on Laravel


php,mysql,laravel,eloquent,laravel-5
My Shema database is User Table id login parent Sign Table id name user_id (Sign owner) Pivot table user_sign id user_id sign_id My User model contain public function signs() { return $this->belongsToMany('App\Sign', 'user_sign'); } public function parent(){ return $this->belongsTo('User', 'parent'); } public function children(){ return $this->hasMany('User', 'parent', 'user_id'); } And...

How can I Echoing Data After Checking For Existence in PHP Laravel 5?


php,laravel,laravel-5
I don't have anything store on my user phone field at the moment. <li><i class="md md-phone"></i> {{ $user->phone or 'No Phone' }} </li> So this line should print out No Phone. But instead it print out as blank. I'm confuse. What did I do wrong /forgot ? Is it because...

Laravel 5: Redirecting woes


laravel
This line works in routes.php: Route::get('faq', '[email protected]'); So I comment it out and try this: Doesn't work when the user is logged in. It will not redirect into the controller action that works in the aforementioned code: Route::get('faq', function() { if (Auth::check()) { return redirect()->action('[email protected]'); } else { return Redirect::to('/');...

Update enum column in Laravel migration using PostgreSQL


postgresql,laravel,laravel-5,laravel-migrations
According to this answer, I have to run a raw query if I want to update an enum in MySQL. But with PostgreSQL, I can't use this query, and enum type for PostgreSQL in Laravel seems strange. Is there any way to update enum in a migration for postgreSQL ?...

What does “as” keyword really mean in Laravel routing?


laravel,laravel-routing
as i understand by laravel documentation, its used for redirection, may be i am not right. i wrote Route::get('user/profile', ['as' => 'profile', function () { echo 'some_text'; }]); then i was expecting my url redicted from https://base_url/public/index.php/user/profile to https://base_url/public/index.php/profile but it doesn't happen. Overall i want to know, what is...

Cannot get parameter value from url in main page


laravel,laravel-5
I searched a lot for the issue. But I couldn't find anything related to getting parameter value from get request in app.blade.php file. URL: http://localhost:8000/project/dashboard/1 I want to get this parameter value after user is signed in. Following is the code in AuthController. if ($this->auth->attempt($request->only('email', 'password'))) { return redirect()->route('dashboard', ['id'...

Laravel Interfaces


php,laravel,interface,namespaces
I used the following tutorial to get an idea about interfaces: http://vegibit.com/what-is-a-laravel-interface/ But I wanted to change the directory of where I am putting my interfaces to "App/Models/Interfaces". And so I did. But now I cannot get it to work anymore. Here is my code: Routes.php App::bind('CarInterface', 'Subaru'); Route::get('subaru', function()...

Handling 500 Internal Server Error from DomDocument in Laravel 5


php,laravel,exception-handling,laravel-5
The library I wrote for Laravel uses DomDocument. I use this library under my Controller, and its namespace is app/Services/Verify/. The library gets initialized and used when I put it some inputs into a form. When the library fails, Laravel would fail the way it would - returning the following...

Querying one-to-one in laravel


php,laravel-4,orm,eloquent
I have two models city and business.I have to perform below queries Find Business by city name. Find Top 10 cities which have the maximum business. Here is the models Business class Business extends \Eloquent { protected $fillable = [ 'business_type', 'first_name', 'last_name', 'email', 'password', 'designation_id', 'name', 'description', 'portfolio_id', 'image',...

Laravel 5 form request validation returning forbidden error


php,validation,laravel,laravel-4,laravel-5
I am trying to use Laravel 5.1's form request validation, to authorize if the request is from the owner. The validation is used when the user is trying to update part of the table clinics through the show.blade.php. My set up so far: routes.php: Route::post('clinic/{id}', array('as' => 'postUpdateAddress', 'uses' =>...

How to change default Nginx setting on Homestead Laravel Virtualbox VM


laravel,nginx,vagrant,virtualbox,homestead
I merely followed the default Laravel Homestead setup here using VirtualBox. Working great. But I need an additional Nginx rewrite setting in my apps vhost file on the VM, something like; location / { if ($request_method !~ "(POST)"){ rewrite .... } try_files $uri $uri/ /index.php?$query_string; } I can add that...

Eloquent model not updating updated_at timestamp


php,laravel,timestamp,eloquent
I'm using Laravel 5.1. To make it simple, I have the following code Migration: Schema::create('sitemap_data', function (Blueprint $table) { // Primary and foreign keys $table->increments('id'); $table->string('postUrl'); // Database functions $table->timestamps(); }); And this is the code somewhere else I'm using $sitemapData = SitemapData::firstOrNew([ 'postUrl' => $post ]); $sitemapData->save(); Now, according...

What is the best practice to implement update profile picture in PHP Laravel 5?


javascript,php,jquery,laravel,laravel-5
I'm trying to allow my user to update their profile photo and I'm wondering what is the best practice to implement something like that in Laravel. Here is my user profile picture. When they hover on it, they will have an option to update their photo. When the user click...

Payum Laravel Package - Route not found


laravel,nvp
I'm using Payum/PayumLaravelPackage Package and I'm having a problem with this package. I have this method: public function prepareExpressCheckout() { $storage = $this->getPayum()->getStorage('Payment'); $details = $storage->create(); $details['PAYMENTREQUEST_0_CURRENCYCODE'] = 'EUR'; $details['PAYMENTREQUEST_0_AMT'] = 1.23; $storage->update($details); $captureToken = App::make('payum.security.token_factory')->createCaptureToken('paypal_ec', $details, 'done'); return \Redirect::to($captureToken->getTargetUrl()); } And...

Laravel relation many to many with additional pivot


php,laravel,laravel-4
Status Update I have implemented morph to many relationship type but how can I insert into the addition field? The code for the polymorphic relation is: public function mailmessages() { return $this->morphToMany('Mailmessage','rel','mailmessage_rels','rel_id','mailmessage_rel_id') ->withPivot(['addition']); } Original Post I have a Laravel project that uses many to many relations and in the...

Messed up a merge when trying to upgrade my Laravel application


git,laravel,github,merge
I have an existing laravel project which used an older version of Laravel 5.1. I wanted to upgrade my project to use Laravel 5.1.2. I followed this tutorial. So I added the laravel/laravel github repository into my git project as a remote called laravel, fetched it, then I created a...

Can't get images from storage laravel 5


php,image,laravel
Hey so i'm trying to put my images into a slideshow i have on my index. the images are saved on storage/app , and then the rest of the path i retrive from my database. I managed to output the correct path on the <img src> tag, and the title...

Admin login laravel 4


php,laravel
I edited the store method , now the problem is that when i try to login it redirect to www.example.com/admin but it shows a NotFoundHttpException. The routes.php file Route::get('/admin', '[email protected]'); Route::get('/logout', '[email protected]'); Route::get('profile', function() { return "welcome! Your username is" . Auth::admin()->username; }); Route::resource('sessions', 'SessionsController', ['only' => ['index', 'create', 'destroy',...

Retreiving a single colum from a pivot table - Laravel 5


php,laravel,eloquent,laravel-5
I am using a pivot table genre_user to relate user to genre. table contains the following fields id user_id genre_id Following are the model definitions User.php public function genres() { return $this->belongsToMany('App\Genre'); } Genre.php public function artists() { return $this->belongsToMany('App\User'); } I am getting the results as a collection when...

Using framework event dispatcher to raise domain event


php,events,laravel,domain-driven-design,dispatcher
When i need to raise domain events, should i use framework specific Event Dispatcher or create my own Event Dispatcher that implemented by framework event dispatcher ? Since the framework has a really nice event dispatcher and the term of DDD said the domain layer should not dependent on any...

Setting up a second Homestead Laravel app


laravel,laravel-5,homestead
I've been trying to set up a second Laravel 5 app on my local Homestead space. I have been following the instructions from the official documentation and from this blog. (Although I have had to use the specific ID of the provision in order to get the vagrant provision command...

Given an array/object of datetimes, how can I return an array/object of the times sorted by hour and times sorted by days of the week


php,arrays,sorting,datetime,laravel
PHP/Laravel, I'm getting an array of objects that includes date times for each record. I need to generate analytics on objects on an hourly basis of a day and daily basis of a week. So for example: For a date range of 1/1/2015 - 1/10/2015 I return 100 records all...

Laravel - Angular Routes


php,angularjs,laravel
I am trying to integrate angular with Laravel 5 and can't get the routes to show content from pages other then the index file. It is not picking up the route under .when() as I can change the templateURL and it has no effect. The files directory is as follows...

Laravel 4.2 Sending email error


php,email,laravel,laravel-4
Hello everyone I have an error in laravel when I am sending an email. I have a form with a select tag and when I select the user and click submit I need to send him a mail after I select it. Here is my Controller method: public function store()...

Set options for ZADD command in laravel redis


php,laravel,redis,set
I'm trying to set options for ZADD with laravel redis but am failing. The option I need to set is NX, as stated in the documentation: ZADD options (Redis 3.0.2 or greater) ZADD supports a list of options, specified after the name of the key and before the first score...

Laravel 4 - Scope to only show rows where another DB has no relational items


laravel-4,eloquent,pivot-table
I have a cars table, and a car_image table. I want to get all the cars that have NO images in the car_image. In my car model I am making a scope: public function scopeNoImages($query) { return $query-> ?? } How can I create a scope that will show only...

Laravel 5 MethodNotAllowedHttpException


php,laravel,laravel-5,laravel-routing
I am using a form with PATCH method and I have a button link(since i already have a submit button and using same form for both store and update) as <a class="btn btn-default" href="{{ URL::to( 'pages/edit/' . $vehicle -> id) }}">EDIT</a> And my route is Route::patch('/pages/edit/{id}', ['uses' => '[email protected]']); Controller...

How to register global variable for my Laravel application?


php,laravel,laravel-5
I have started with Laravel a few days ago, and today I just installed the vespakoen/menu that seems to be very nice, and probably will work for what I need it. Currently I have installed Laravel 5.1 on my system. The problem I currently have, is where to register my...

Laravel5: Access public variable in another class


php,class,oop,laravel,laravel-5
I have a middleware file called LanguageMiddleware.php: ... class LanguageMiddleware { //ISO language codes: public $languages = ['en','es','fr','de','pt','pl','zh','ja']; ... LanguageMiddleware.php is in laravelProj/app/Http/Middleware/ Here's my problem: I have a blade template file called master.blade.php where I'm attempting to output a list of languages @foreach (App\Http\Middleware\LanguageMiddleware\languages as $lang) <a class=\"setLang\" href=\"lang/en\">{{...

Laravel get posts with multiple tags


php,sql-server,laravel,eloquent
I'm working with a laravel belongsToMany relationship between Post and Tag. What I'm trying to do is get all Posts where it has multiple tags. I've tried all sorts of eloquent queries, but I can't get it at all. Currently I can get an array of post_id's and tag_id's, as...

Laravel validator vs requests


laravel,laravel-5,laravel-validation
Hello, I want to understand how to handle data validation with Laravel 5. I see that this can be done using or the validator, or the request files. The thing is that there are many points I didn't get. What is the difference between using a request file for validation...

laravel 5.1 not seeing changes to Job file without VM restart


php,laravel,laravel-5,homestead
I have created a new Job in a laravel 5.1 app, running in Homestead VM. I've set it to be queued and have code in the handle method. The handle() method previous expected a param to be passed, but is no longer required and I've removed the param form the...

How to delete only the table relationed


sql,laravel,migration
I know how to create the migrations with laravel 5.1 and I have the following code public function up() { Schema::create('articulos', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->string('content'); $table->integer('categoria_id')->unsigned(); $table->integer('creador_id')->unsigned(); $table->string('slug', 32); $table->timestamps(); }); Schema::table('articulos', function($table) { $table->foreign('categoria_id')->references('id')->on('categorias');...

laravel file uploading using json


jquery,ajax,json,laravel,laravel-5
I am using laravel 5. I have did the following code to post data using json to my controller. But I cannot make file uploading by this manner. e.preventDefault(); $.ajax({ type: 'POST', cache: false, dataType: 'JSON', url: 'tasks', data: $('#my_form').serialize(), success: function(data) { console.log(data); }, }); I have the following...

Laravel 5: How to add Auth::user()->id through the constructor ?


authentication,laravel,constructor
I can get the ID of the authenticated user like this: Auth::user()->id = $id; Great it works, ... but I have a load of methods which need it and I want a cleaner way of adding it to the class as a whole,so I can just reference the $id in...

How to cut the content in laravel5?


php,laravel
I need to cut the characters that show description with the same quantity of letter in all foreach. Could anyone helps me? @foreach ($subastas as $subasta) @if(($subasta->data_inici <= $data)&&($subasta->data_final>$data)) <a href="item/{{$subasta->id}}"><div class="col-sm-4"> <div class="product-image-wrapper"> <div class="single-products"> <div class="productinfo text-center"> <div class="nombre">{{$subasta->nombre}}</div> @foreach ($subasta->images as $word =>...

PDF as mail attachment - Laravel


laravel,pdf,sendmail
I want to create a PDF using the barryvdh/laravel-dompdf package and send this with an email as attachment. The code I have now is: $pdf = PDF::loadView('layouts.factuur', array('factuur' => $factuur)); Mail::queue('emails.factuur', array('factuur' => $factuur), function($message) use ($pdf) { $message->to(Input::get('email'), Input::get('naam'))->subject('Onderwerp'); $message->attach($pdf->output()); }); But now I get the following error: Serialization...

Laravel belongsTo throwing undefined function App/BelongsTo() exception


php,sql,laravel,eloquent,belongs-to
I have a comments table and user table with the relationship: user->hasMany('comments') and comment->belongsTo('user'). For some reason with which eludes me, I keep getting this FatalErrorException in Comment.php line 22: Call to undefined function App\belongsTo() My other models have no issue whatsoever with the HasMany relations, however, the comments model...

problems understanding workflow and set up of vagrant and laravel homestead


laravel,vagrant,virtual-machine,homestead
Up till now I've used a wamp server and thought I'd give Laravel Homestead a try as it's meant to be easier! I'm having problems getting the set up right and I'm confused about what I'm doing and where I should be doing them. I've got vagrant and virtual box...

Getting code from my forked repository


git,laravel,repository,laravel-5,composer-php
I made a fork from a repository called "chrisbjr/api-guard". the repository latest version is v2.2.2, and I made a release v2.2.3 from my fork. I have my own branch which is dev-fulluth, to get the code from my fork not from the main repo, composer has to contain the below...

Join this eloquent laravel5


php,laravel
I recieve correctly this two messages , but I need to JOIN this two results with Laravel5. Could anyone helps to me ? Or it's any possibilities to doing this with other form? $mensajes = Messageuser::find(1)->conversaciones()->get(); $mensajes2 = Messageuser::find(4)->conversaciones()->get(); echo $mensajes; echo $mensajes2; UPDATE The MessageUser use Illuminate\Database\Eloquent\Model; class MessageUser...

Laravel Production issue - Updating composer with Laravel 4.1.x


php,laravel,composer-php
I haven't encountered any issue in deploying my laravel project until now. I've been deploying for like almost a year already for this project. But some new bug came up. First of all. I can't run composer update, cause it says this error. composer update Warning: This development build of...

Laravel 5 pagination with trailing slash redirect to 301


php,laravel,redirect,pagination,laravel-5
I'm using Laravel 5 and notice that the pagination is adding a trailing slash before the ?page=# and with that, it always redirect to a 301 page. http://example.com/news/articles/?page=2 will do a 301 redirect to http://example.com/news/articles?page=2 This is causing my pagination using ajax to slow down because it is having 2...

2 Foreach Loop Inside A Table


php,loops,laravel-4,foreach,blade
I had Users table and group table, when i load a group table, it loads the user which have same group_id as the group table id. it works, but my problem is the foreach was quite a mess. the output looks like this.. however, i want to make the output...

Nested comments with Laravel


php,mysql,laravel,laravel-4
I'm currently trying to replicate something similar to a forum, but I'm stumped on how I could create nested comments. I understand that for regular replies I could create a replies table and run a loop for each comment that matches the thread id. But I don't know how I...