Create a Third Table With Laravel (eloquent)
I hope you can help me with this exercise. I have to track the entry and exit of each person and display it in one row.
The models created so far are people and movements with the following relationships:
Person-> hasMany (Movement :: class);
Movement-> belongsTo (Person :: class);
Created the two tables and relations, now I have to create the third (person_movements). I am attaching the very descriptive scheme directly here 👇
Thanks for your help 🙏😊
do you know?
how many words do you know
See also questions close to this topic
-
delete a table form a database using laravel command
i need to delete a database table using laravel artisan command . not like this command php artisan migrate:rollback --step=5
i need to create like this route or controller code .
Route::get('/clear/database', function () {
Artisan::call('cache:clear'); return redirect('/');
});
. i also try public function dd()
{ Schema::drop('table_name'); }
but it not working . gives me error like this SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table
table_name
)no foreign key for the table . what should i do ?
thanks in advance!
-
Foreach for Categories
i have this data, I want to loop with categories for each question. Right now all I can do is loop by displaying sequentially for each question (as in the image).what I want to do is loop and group them based on categories_id , if the categories_id changes it will be given a new line.
// 20220507095412 // http://127.0.0.1:8000/user/exams [ { "id": 16, "ujians_id": 11, "questions_id": 3, "mulai": null, "berakhir": null, "durasi": 60, "isAnswer": 0, "created_at": "2022-05-07T02:53:56.000000Z", "updated_at": "2022-05-07T02:53:56.000000Z", "questions": { "id": 3, "title": "2", "question": "<p>Sarana yang sangat masih dalam menyebabkan oposisi dunia yang sering berdampak pada intervensi asing terhadap Indonesia pada era globalisasi sekarang ini adalah...</p>", "img": null, "categories_id": 1, "created_at": "2022-05-07T02:11:41.000000Z", "updated_at": "2022-05-07T02:11:41.000000Z" } }, { "id": 17, "ujians_id": 11, "questions_id": 1, "mulai": null, "berakhir": null, "durasi": 60, "isAnswer": 0, "created_at": "2022-05-07T02:53:56.000000Z", "updated_at": "2022-05-07T02:53:56.000000Z", "questions": { "id": 1, "title": "13", "question": "<p>Wahidin soedirohoesodo memilik peran penting dalam pergerakan kemerdekaan. Antara lain…22234232</p>", "img": null, "categories_id": 1, "created_at": "2022-05-02T10:39:13.000000Z", "updated_at": "2022-05-03T13:28:24.000000Z" } } ]
@php $no=1 @endphp @foreach($dataUjian as $row) @if($row->isAnswer == 0) <button class="btn btn-primary btn-sm" onclick="getUjian({{$row->questions_id}}, {{$row->id}},{{$row->ujians->users_id}})" >{{$no++}}</button> @else <button class="btn btn-danger btn-sm" disabled>{{$no++}}</button> @endif @endforeach
-
Unit testing with get request
I am trying to create a unit test for one of my api.
In the frontend, I send it this way...
params = { participants: JSON.stringify(participants), section: JSON.stringify(section), }; axios.get('/api/list', params)
while in the controller, it receives the params this way...
public function list(Request $request) { $participants = json_decode($request->participants); $section = json_decode($request->section); }
Now, I tried making a unit test out of this. by doing...
$params = [ 'participants' => ['id', 'name', 'rating'], 'section' => ['id', 'code'], ]; $this->get('/api/list'.http_build_query($params))->assertStatus(200) // $this->json('/api/list', $params)->assertStatus(200) // -> also tried this one // $this->getJson('/api/list', $params)->assertStatus(200) // -> also tried this one // $this->call('GET', '/api/list', $params)->assertStatus(200) // -> also tried this one
But none of them works, it always says
TypeError: json_decode(): Argument #1 ($json) must be of type string, array given
.So, the way I built the url and the params must be all wrong,
so my question here is that, what's the correct way of building the url so that it provides a correct url string format and the controller will json_decode the params?
-
How can I write the sql query as a laravel query?
I have a query like this, I want to write it as laravel query builder. I tried this, it gave an error, how can I do it?
This is the query I want to write
select u.id as user_id, u.nick_name, sum(v.total_ticket) as ticket from bogo_video_prop as v LEFT JOIN bogo_user as u on u.id = v.to_user_id where u.is_effect=1 and v.is_red_envelope = 0 GROUP BY v.to_user_id order BY sum(v.total_ticket) desc limit 10
This is the query I tried(The bogo_video_prop table, which I named TopPublisher)
$top_publishers = TopPublisher::select('id', 'nick_name', DB::raw('sum(total_ticket) as ticket')) ->leftJoin('bogo_user', 'bogo_user.id', '=', 'bogo_video_prop.to_user_id') ->where('bogo_user.is_effect', 1) ->where('bogo_video_prop.is_red_envelope', 0) ->groupBy('bogo_video_prop.to_user_id') ->orderBy('ticket', 'desc') ->limit(10) ->get();
-
How to include model attribute automatically?
I have the
User
model which define the following attribute:public function getAvatarUrlAttribute() { return 'https://i.pravatar.cc/300?u=' . $this->email; }
I usually access to this attribute using something like:
User::find(1)->avatar_url;
Problem
I need to return all the attributes of the
User
model when I execute this code:$users = User::whereRoleIs('doctor')->get();
The collection returned to
ajax
doesn't containavatar_url
attribute though. How can I include all the attributes automatically?Thanks.
-
Eloquent order model by its relationship hasManyTrough
I have 3 tables
products
,product_categories
andcategories
product_categories
is a pivot table that help me on the relationship betweenproducts
&categories
.The relation is as follow in
Product.php
model:public function categories() { return $this->hasManyThrough(Category::class, ProductCategory::class, 'product_id', 'id', 'id', 'category_id'); }
So now I need to query the products so I am doing the following:
Product::with('options') ->with('options.price') ->with('categories') ->paginate(25);
I can not find the way to sort my products list by the category name on the categories table...
is there any way?
My products table is quite large so it wont be possible to get all the results first and then
sortBy()->take(25);
EDIT
The categories table has multiple categories and subcategories... the product_categories relate products with only subcategories... Basically what I want is to sort the products by the main category
-
My coding mistake or problem with the integrity of the data?
I'm learning Laravel from Laracasts videos and so far I've made simple blog with 4 posts that are dynamic but only 2 of them when I click on the name of the post open up the other 2 show error 404 not found
Example of a working one - https://ctrlv.cz/dgUM Example of a not working one - https://ctrlv.cz/MZrP
web.php code with routes
<?php use Illuminate\Support\Facades\Route; use App\Models\Post; use Spatie\YamlFrontMatter\YamlFrontMatter; Route::get('/', function () { $files = File::files(resource_path("posts")); $posts = []; foreach ($files as $file) { $document = YamlFrontMatter::parseFile($file); $posts[] = new Post( $document->title, $document->excerpt, $document->date, $document->body(), $document->slug ); } return view('posts', [ 'posts' => $posts ]); }); Route::get('posts/{post}', function ($slug) { return view ('post', [ 'post' => Post::find($slug) ]); })->where('post', '[A-z_\-]+');
post.php
<?php namespace App\Models; use Illuminate\Support\Facades\File; class Post { public $title; public $excerpt; public $date; public $body; public $slug; public function __construct($title, $excerpt, $date, $body, $slug) { $this->title = $title; $this->excerpt = $excerpt; $this->date = $date; $this->body = $body; $this->slug = $slug; } public static function all() { $files = File::files(resource_path("posts/")); return array_map(fn($file) => $file->getContents(), $files); } public static function find($slug) { if (! file_exists($path = resource_path("posts/{$slug}.html"))) { throw new ModelNotFoundException(); } return cache()->remember("posts.{$slug}", 3600, fn() => file_get_contents($path)); } }
-
How to check authorization before loading Route Model Binding
I ask this question after doing various searches without finding any clarifying information that helps me solve the problem that I am presenting.
I have created a controller with the following command:
php artisan make:controller UserController --api -m User -r -R
Which creates the controller and the FormRequest classes. Inside the controller, let's just focus on the
'update'
method, since that's the one I'm having some trouble with.<?php namespace App\Http\Controllers; use App\Http\Requests\StoreUserRequest; use App\Http\Requests\UpdateUserRequest; use App\Models\User; class UserController extends Controller { /** * Update the specified resource in storage. * * @param \App\Http\Requests\UpdateUserRequest $request * @param \App\Models\User $user * @return \Illuminate\Http\Response */ public function update(UpdateUserRequest $request, User $user) { // } ...
As you can see from the method arguments, this method uses what we call Route Model Binding
After this, I define my route in the routes file
'api.php'
as follows:<?php use App\Http\Controllers\UserController; use Illuminate\Support\Facades\Route; Route::middleware('auth:sanctum')->group(function () { Route::apiResource('user', UserController::class); });
Which registers all the routes and within them the
'update'
route.In the FormRequest class named
'UpdateUserRequest'
, which uses the'update'
method in the previously created controller, I define the'authorize'
method to return false on all checks just for testing. The class would look similar to this:<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; class UpdateUserRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return false; } ...
Now, the problem that I am presenting, when I access the route:
http://127.0.0.1:8000/api/user/100?
Using Postman, I make a request to that route with the
PUT
method and Laravel returns the following error:{ "message": "No query results for model [App\\Models\\User] 100" }
This is because I don't have a
user
with'id'
100, I only have 2 users in my database for testing purposes.My question is this: Isn't Laravel supposed to return an error on this request? Telling me that the action is not allowed, since in the FormRequest
'UpdateUserRequest'
class, in the'authorize'
method, I always returnfalse
.I think Laravel is loading the middleware
\Illuminate\Routing\Middleware\SubstituteBindings::class
before middleware\Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class
.I know that in the
app/Http/Kernel.php
file I can modify the middleware priority, overriding the$middlewarePriority
property, but I've tried it and I don't get the expected result.Because from my perspective, it doesn't make much sense, taking the previous example that a user who doesn't have permissions to update the model
User
tries to access the route and Laravel returns an error saying that the user trying to modify with thatid
exists or not, without first verifying that the user trying to perform the(update)
action has or does not have permissions to perform it. -
http to https and www to non-www not working correct with laravel 8 URI links
I searched a lot of about this topic to redirect all urls to https://my-domain
I want delete the www and add https.
I found a lot of answers this one work good
<IfModule mod_rewrite.c> RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} ^www\. [NC] RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301] </IfModule>
but the problem its just working with the home page link. for example: when I write
https://www.example.com it redirect to => https://example.com
but the problem is when i try: https://www.example.com/about-us
its redirect ti https://example.com/index.php how can i solve that I am using Laravel 8
I want all type of URL to non-www and https. and how can I redirect index.php and index.html to https://example.com/
This is my .htaccess file:
<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} ^www\. [NC] RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301] </IfModule>
-
Count condition in Laravel eloquent collection
I have this part of my eloquent query in Laravel 8
$voters = Voter::where('municipality', $user->municipality)->select(['status','leader', 'position'])->get(); for($i = 0; $i < $brgys; $i++){ //$voters = $voters_municipalities->where('brgy', $barangays['brgy'][$i])->get(); $brgy_leader_info = $voters->where('brgy', $barangays['brgy'][$i])->where('position', '=', 'Leader')->count(); $brgy_bac = $voters->where('brgy', $barangays['brgy'][$i])->where('position', '=', 'BAC')->count(); $brgy_bac_leader = $voters->where('brgy', $barangays['brgy'][$i])->where('position', '=', 'BAC Leader')->count(); $brgy_precint_coordinator = $voters->where('brgy', $barangays['brgy'][$i])->where('position', '=', 'Precint Coordinator')->count(); $brgy_voters_bucg_voters = $voters->where('brgy', $barangays['brgy'][$i])->where('position', '=', 'Voter')->where('status', 2)->count(); $brgy_voters_bucg_members = $voters->where('brgy', $barangays['brgy'][$i])->where('position', '=', 'Voter')->where('leader','!=',0)->where('status', 2)->count(); $brgy_voters_bucg_voter_no_leader = $voters->where('brgy', $barangays['brgy'][$i])->where('position', '=', 'Voter')->where('status', 2)->where('leader', 0)->count(); $brgy_voters_bucg = $voters->where('brgy', $barangays['brgy'][$i])->where('status', 2)->count(); $brgy_leader['brgy'] =$barangays['brgy'][$i]; $brgy_leader['leader_count'] = $brgy_leader_info; $brgy_leader['brgy_bac'] = $brgy_bac; $brgy_leader['brgy_bac_leader'] = $brgy_bac_leader; $brgy_leader['brgy_precint_coordinator'] = $brgy_precint_coordinator; $brgy_leader['brgy_voters_bucg_voters'] = $brgy_voters_bucg_voters; $brgy_leader['brgy_voters_bucg_members'] = $brgy_voters_bucg_members; $brgy_leader['brgy_voters_bucg'] = $brgy_voters_bucg; $brgy_leader['brgy_voters_bucg_voter_no_leader'] = $brgy_voters_bucg_voter_no_leader; $leaders_count += $brgy_leader_info; array_push($brgy_leaders, $brgy_leader); }
inside in the for loop is my previous query the commented line but it took 20+ seconds to load depending on the amount of data. So I tried to move up outside the loop but still got maximum execution time error. Somebody I do not have idea how can I make this more faster.
-
Return data with pivot field Laravel Api
I want to return a role with permissions of it through pivot table, relationship, but when I write:
$role = $this->roleRepository->detail($id); $data = ([ "role" => $role ]);
postman just return:
"data": { "role": { "id": 12, "name": "grand-admin" } }
I write:
$role = $this->roleRepository->detail($id); $data = ([ "role" => $role, "hasPermission" => $role->permissions ]);
Postman return:
"data": { "role": { "id": 12, "name": "grand-admin", "permissions": [ { "id": 1, "name": "view_customer", "pivot": { "role_id": 12, "permission_id": 1 } }, { "id": 1, "name": "view_customer", "pivot": { "role_id": 12, "permission_id": 1 } } ] }, "hasPermission": [ { "id": 1, "name": "view_customer", "pivot": { "role_id": 12, "permission_id": 1 } }, { "id": 1, "name": "view_customer", "pivot": { "role_id": 12, "permission_id": 1 } } ] }
Problem is loop 2 times data of permission, how can I write to return only the upper part.