Storage class in query builder - ajax

I have an ajax request in JSON and I need to return a file path, to download a file.
I get the storage like this:
$attachments = $req->file('files')[$key][0]->storeAs('purchase', $filename);
I have symlinked the storage:
php artisan storage:link
In my controller I do the following:
$dataAttachments = DB::table('purchase_requests_attachments AS a')
->join('users AS b', 'a.id_usr_add', '=', 'b.id')
->join('purchase_attachments_rules AS c', 'a.id_rule', '=', 'c.id')
->select(DB::RAW(Storage::download('a.file', 'tituloteste')), 'a.id AS id', 'a.id_usr_add AS id_usr', 'b.full_name AS full_name', 'a.id_rule AS id_rule', 'c.description as description', 'a.file AS attachment', 'a.created_at AS created_at')->where('a.id_request', '=', $id_purchase)->get();
The raw doesn't work to return the path to request.
The raw method does not seem to return the correct path.
Thank you!

Related

I have laravel project working fine in localhost but after i've added new routes, url and views it says 404 Not Found in Cpanel only works localhost

Can you please assist, I have laravel project working fine in my localhost where am using wamp.The problem arise after uploading the project to cpanel it says 404 Not found to new routes i just added and others works fine. I tried stackoverflow asked questions where the found .htaccess solutions but still didn't help.
Error 404 Not Found Screenshot
**Here is my Web.php file**
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ExcelController;
//admin
Route::group(['middleware' => ['auth', 'role:admin'] ], function() {
Route::get('/admin/clientsaccounts', 'App\Http\Controllers\AdminController#accountsHome')->name('admin.clientsaccounts.index');
Route::get('/admin/accstatements', 'App\Http\Controllers\AdminController#statements')->name('admin.accstatements.index');
});
Controller
public function statements(Request $request){
$search = $request->input('search');
$custacc =DB::table('customers')
->select('customers.*')
->where('customers.firstname', 'LIKE', "%{$search}%")
->orWhere('customers.surname', 'LIKE', "%{$search}%")
->orWhere('customers.idnumber', 'LIKE', "%{$search}%")
->orderby('customers.created_at', 'desc')
->get();
return view('admin.statements.index')->with(compact('custacc'));
}
public function accountsHome(Request $request){
$search = $request->input('search');
$custacc =DB::table('accounts')
->join('customers', 'accounts.idnumber', '=', 'customers.idnumber')
->select('customers.*', 'accounts.*')
->where('customers.firstname', 'LIKE', "%{$search}%")
->orWhere('customers.surname', 'LIKE', "%{$search}%")
->orWhere('accounts.idnumber', 'LIKE', "%{$search}%")
->orderby('accounts.created_at', 'desc')
->paginate(10);
return view('admin.accounts.index')->with(compact('custacc'));
}
Laravel caching system also takes routes in consideration, to remove route cache in Laravel use the given below command:
php artisan route:cache
you need to clear route cache in your laravel application.
put following code to your route and all request will works fine.
now, when you create new route; you just have to run this route.
use Illuminate\Support\Facades\Artisan;
Route::get('/clear-cache', function() {
Artisan::call('cache:clear');
return "Cache is cleared";
});
You need to clear you rout cache every time you add new routes same with your view. With latest Laravel you can use artisan optimize in your command line or use the Route configuration.
use Illuminate\Support\Facades\Artisan;
Route::get('/optimize', function() {
Artisan::call('optimize');
return "Website is optimized";
});

add new element in laravel collection for friendship in laravel

I am trying to display all users weather I send him friend request or not with friendship status for that. First of all I load all friend requests and received request in that manner.
$users2 = User::with(['sentRequests' => function ($query) {
...
}])->with(['recievedRequests' => function ($query) {
...
}])->where('users.id', Auth::id())->get();
But then I also want to load other users so for that I create some query like that
$sent = Friendship::where('user_id', Auth::id())
->pluck('friend_id');
$received = Friendship::where('friend_id', Auth::id())
->pluck('user_id');
$users3 = User::whereNotIn('id', $sent)
->whereNotIn('id', $received)
->where('id', '!=', Auth::id())
->get();
Now I want to append $users3 to $users2 but when I done like that
$users2->put('otherUsers',$users3);
It appended but not in the right manner , I want to append it in same manner as 'sentRequests' and 'recievedRequests' are.

How create a subquery with eloquent and laravel with softdeletes

I am using Laravel 7 and Vue.js 2.
I want to retrieve the tasks that are not assigned to a specific user.
I made the following code that works correctly.
$tasks_user = TaskUser::select('task_id')
->where('user_id', $id)
->get();
$tasks = Task::select('tasks.id as id', 'tasks.name as name', 'tasks.description as description')
->join('task_user', 'tasks.id', '=', 'task_user.task_id')
->whereNotIn('task_user.task_id', $tasks_user)
->distinct()
->get();
By the way to be more elegant I decided to transform the above code into a single query as follows:
$tasks = Task::select('tasks.id as id', 'tasks.name as name', 'tasks.description as description')
->join('task_user', 'tasks.id', '=', 'task_user.task_id')
->whereNotIn('task_user.task_id', function($q) use ($id)
{
$q->select('task_id')
->from('task_user')
->where('user_id', $id)
->get();
})
->distinct()
->get();
Unfortunately I discovered that the above query didn't work because it doesn't considers softdeletes.
For example, if the user with id 3 was related with the task 7 but now that row has been deleted with softdeletes in the table task_user, the first code returns also the task with id 7 (correctly) and the second one not (uncorrectly).
So finally, I must do a single query that works as the first code.
Can help?
You can actually combine both approaches. whereNotIn accepts also an Eloquent Query, it doesnt need to be a callback. Try this:
$userRelatedTasksQuery = TaskUser::select('task_id')
->where('user_id', $id);
$tasks = Task::select('tasks.id as id', 'tasks.name as name', 'tasks.description as description')
->join('task_user', 'tasks.id', '=', 'task_user.task_id')
->whereNotIn('task_user.task_id', $userRelatedTasksQuery)
->distinct()
->get();
Be sure to not use get() at the end of the $userReleatedTasksQuery, as you want the eloquent query instance, not the result.

laravel send mail to

Good evening everyone, I have some issues, with send mail to:
I have a code in controller, and have data taken from database with joins, this $survey variable shows gives me emails of the survey which belongs to team.
But I need some how to send an email for all emails which I gets from $survey variable. When I put $survey variable inside $message->to($survey); it shows me Undefined variable
my code below , how can I use it. When I put in ->to(); normal one email adress it works, but I need to send same email to all team members
public function startSurvey(Request $req) {
$nameSurvey = $req->input('SurveySelectBox');
$startDate = $req->input('surveyStartDate');
$endDate = $req->input('surveyEndDate');
$data = array(
'updated_at' => Carbon::now(),
'started_at' => $startDate,
'ended_at' => $endDate
);
DB::table('survey')->where('surveyId','=',$nameSurvey)->update($data);
$survey = Survey::where('surveyId' , '=', $nameSurvey)
->join('team','team.teamId', '=', 'survey.teamId')
->join('teammembersall','teammembersall.TeamId', '=', 'team.TeamId')
->join('users','users.id', '=', 'teammembersall.UserId')
->select('users.email')
->get();
Mail::raw('You have new survey to answer: http://localhost:8000/profile', function ($message) {
$message->from('kristijanask#gmail.com', 'New Survey released');
$message->to($survey);
});
return redirect('surveyDrafts');
}
You need to use use ($survey) to use the variable within the Mail anonymous function:
Mail::raw('...text', function ($message) use ($survey) {
$message->from('kristijanask#gmail.com', 'New Survey released');
$message->to($survey);
});
You might also need to use ->pluck() and toArray() on the query result, to make the result an array:
$survey = Survey::where('surveyId' , '=', $nameSurvey)
// long query
->get()
->pluck('email')
->toArray();

Laravel eloquent and relationship

I have a code:
$response = $this->posts
->where('author_id', '=', 1)
->with(array('postComments' => function($query) {
$query->where('comment_type', '=', 1);
}))
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
And when I logged this query with:
$queries = \DB::getQueryLog();
$last_query = end($queries);
\Log::info($last_query);
In log file I see follow:
"select * from `post_comments` where `post_comments`.`post_id` in (?, ?, ?, ?) and `comment_type` <> ?"
Why is the question mark for comment_type in the query?
Update #1:
I replaced current code with following and I get what I want. But I'm not sure it is OK. Maybe exists many better, nicer solution.
$response = $this->posts
->where('author_id', '=', 1)
->join('post_comments', 'post_comments.post_id', '=', 'posts.id')
->where('comment_type', '=', 1)
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
Behind the scene the PDO is being used and it's the way that PDO does as a prepared query, for example check this:
$title = 'Laravel%';
$author = 'John%';
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));
In the run time during the execution of the query by execute() the ? marks will be replaced with value passed execute(array(...)). Laravel/Eloquent uses PDO and it's normal behavior in PDO (PHP Data Objects). There is another way that used in PDO, which is named parameter/placeholder like :totle is used instead of ?. Read more about it in the given link, it's another topic. Also check this answer.
Update: On the run time the ? marks will be replaced with value you supplied, so ? will be replaced with 1. Also this query is the relational query, the second part after the first query has done loading the ids from the posts table. To see all the query logs, try this instead:
$queries = \DB::getQueryLog();
dd($queries);
You may check the last two queries to debug the queries for the following call:
$response = $this->posts
->where('author_id', '=', 1)
->with(array('postComments' => function($query) {
$query->where('comment_type', '=', 1);
}))
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
Update after clarification:
You may use something like this if you have setup relation in your Posts model:
// $this->posts->with(...) is similar to Posts::with(...)
// if you are calling it directly without repository class
$this->posts->with(array('comments' =. function($q) {
$q->where('comment_type', 1);
}))
->orderBy('created_at', 'DESC')->limit($itemno)->get();
To make it working you need to declare the relationship in your Posts (Try to use singular name Post if possible) model:
public function comments()
{
return $this->hasmany('Comment');
}
Your Comment model should be like this:
class Comment extends Eloquent {
protected $table = 'post_comments';
}

Resources